/**
 * Dashboard Staff Reply API
 *
 * POST /api/dashboard/whatsapp-conversations/[id]/reply
 * Lets a staff user take over a WhatsApp conversation and send a
 * manual reply. Sending a reply flips the conversation into
 * humanControlled mode so the AI stops responding.
 */

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 { twilioWhatsAppService } from "@/lib/services/twilio-whatsapp.service";
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 message =
      typeof body?.message === "string" ? body.message.trim() : "";

    if (!message) {
      return NextResponse.json(
        { success: false, error: "Message is required" },
        { status: 400 },
      );
    }

    if (message.length > 4000) {
      return NextResponse.json(
        { success: false, error: "Message too long" },
        { status: 400 },
      );
    }

    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 },
      );
    }

    // Send via Twilio. (Meta path can be added later — for now Twilio is
    // the only configured outbound channel in the dev environment.)
    const credentials =
      await twilioWhatsAppService.getCredentialsForOrg(organizationId);

    if (!credentials) {
      return NextResponse.json(
        {
          success: false,
          error: "WhatsApp is not connected for this organization",
        },
        { status: 400 },
      );
    }

    const to = conv.userPhone?.startsWith("whatsapp:")
      ? conv.userPhone
      : `whatsapp:${conv.userPhone}`;

    const sendResult = await twilioWhatsAppService.sendTextMessage(
      credentials,
      to,
      message,
    );

    if (!sendResult.success) {
      return NextResponse.json(
        {
          success: false,
          error: sendResult.error || "Failed to send message",
        },
        { status: 502 },
      );
    }

    // Persist the staff message so it shows up in the conversation log.
    const created = await prisma.org_whatsapp_messages.create({
      data: {
        conversationId: id,
        role: "staff",
        content: message,
        language: conv.language ?? "en",
        toolsUsed: [],
        metadata: {
          twilioMessageSid: sendResult.messageSid ?? null,
          sentBy: user.userId,
        },
        timestamp: new Date(),
      },
    });

    // Flip the conversation into human-controlled mode.
    await prisma.org_whatsapp_conversations.update({
      where: { id },
      data: {
        humanControlled: true,
        humanControlledAt: new Date(),
        humanControlledBy: user.userId,
        lastMessageAt: new Date(),
        messageCount: { increment: 1 },
        updatedAt: new Date(),
      },
    });

    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const createdRow = created as any;

    return NextResponse.json({
      success: true,
      data: {
        messageId: createdRow?.id ?? createdRow?._id ?? null,
        messageSid: sendResult.messageSid ?? null,
      },
    });
  } catch (error) {
    logger.error("Dashboard conversation reply error", {
      error: error instanceof Error ? error.message : String(error),
    });
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
}
