/**
 * Dashboard Handoff Toggle API
 *
 * POST /api/dashboard/whatsapp-conversations/[id]/handoff
 * Toggles humanControlled on a conversation. When enabled, the AI
 * engine stops auto-responding so a staff member can take over.
 */

import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { prisma } from "@/lib/db";
import { getAuthenticatedUser } from "@/lib/utils/auth-helpers.util";
import { getEffectiveDataOwnerId } from "@/lib/utils/organization-data";
import { logger } from "@/lib/logger";

export const dynamic = "force-dynamic";

export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> },
) {
  try {
    const { id } = await params;

    const user = await getAuthenticatedUser(request, auth);
    if (!user) {
      return NextResponse.json(
        { success: false, error: "Unauthorized" },
        { status: 401 },
      );
    }

    const { organizationId } = await getEffectiveDataOwnerId(user.userId);
    if (!organizationId) {
      return NextResponse.json(
        { success: false, error: "No organization" },
        { status: 403 },
      );
    }

    const body = await request.json().catch(() => ({}));
    const humanControlled = Boolean(body?.humanControlled);

    const conversation = await prisma.org_whatsapp_conversations.findUnique({
      where: { id },
    });

    if (!conversation) {
      return NextResponse.json(
        { success: false, error: "Conversation not found" },
        { status: 404 },
      );
    }

    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const conv = conversation as any;

    if (conv.organizationId !== organizationId) {
      return NextResponse.json(
        { success: false, error: "Access denied" },
        { status: 403 },
      );
    }

    await prisma.org_whatsapp_conversations.update({
      where: { id },
      data: {
        humanControlled,
        humanControlledAt: humanControlled ? new Date() : null,
        humanControlledBy: humanControlled ? user.userId : null,
        updatedAt: new Date(),
      },
    });

    return NextResponse.json({
      success: true,
      data: { humanControlled },
    });
  } catch (error) {
    logger.error("Dashboard conversation handoff error", {
      error: error instanceof Error ? error.message : String(error),
    });
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
}
