/**
 * Dev-only: invoke the WhatsApp AI engine directly with a question and return
 * the response text. Skips Twilio signature validation, webhook parsing, and
 * message delivery so we can verify knowledge-base retrieval end-to-end from
 * curl without bouncing through WhatsApp Web + ngrok + Twilio.
 *
 * POST /api/dev/ai-ask
 *   body: { message: string, phone?: string, language?: "en"|"ar" }
 *
 * Gated on ENABLE_DEV_ROUTES=1.
 */

import { NextRequest, NextResponse } from "next/server";
import { whatsAppAIEngine } from "@/lib/services/whatsapp-ai-engine.service";
import { twilioWhatsAppService } from "@/lib/services/twilio-whatsapp.service";
import { getSectorConfigForIndustry } from "@/lib/config/sector-registry";
import type {
  ConversationContext,
  BookingFlowState,
} from "@/lib/types/twilio-whatsapp.types";

export async function POST(req: NextRequest) {
  if (process.env.ENABLE_DEV_ROUTES !== "1") {
    return NextResponse.json({ error: "Dev routes disabled" }, { status: 403 });
  }

  try {
    const body = await req.json().catch(() => ({}));
    const message = String(body?.message || "").trim();
    const phone = String(body?.phone || "+447500000001");
    const language = (body?.language === "ar" ? "ar" : "en") as "en" | "ar";

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

    const twilioNumber = process.env.TWILIO_WHATSAPP_NUMBER;
    if (!twilioNumber) {
      return NextResponse.json(
        { error: "TWILIO_WHATSAPP_NUMBER not set" },
        { status: 500 },
      );
    }

    const org = await twilioWhatsAppService.getOrgByTwilioNumber(twilioNumber);
    if (!org) {
      return NextResponse.json(
        { error: "org not found for TWILIO_WHATSAPP_NUMBER", twilioNumber },
        { status: 404 },
      );
    }

    const sectorConfig = getSectorConfigForIndustry(
      (org as unknown as { industry?: string }).industry ?? "",
    );

    // Accept incoming conversationState so a test can chain multi-turn
    // flows (e.g. awaiting_cancel_confirmation → YES) without the full
    // Twilio webhook round-trip.
    const incomingState = (body?.conversationState ?? {
      phase: "idle",
    }) as BookingFlowState;

    const context: ConversationContext = {
      organizationId: org.id,
      organizationName: org.name,
      customerPhone: phone,
      customerName: body?.customerName || "Dev Test User",
      language,
      conversationHistory: Array.isArray(body?.conversationHistory)
        ? body.conversationHistory
        : [],
      conversationState: incomingState,
      isReturningCustomer: false,
      industry: (org as unknown as { industry?: string }).industry,
    };

    const result = await whatsAppAIEngine.processMessage(
      context,
      message,
      sectorConfig,
    );

    return NextResponse.json({
      ok: true,
      org: { id: org.id, name: org.name },
      question: message,
      response: result.responseText,
      intent: result.intent,
      action: result.action,
      newState: result.newState,
      bookingId: (result as unknown as { bookingId?: string }).bookingId,
      kbUsed: (result as unknown as { kbUsed?: boolean }).kbUsed,
      kbConfidence: (result as unknown as { kbConfidence?: number })
        .kbConfidence,
    });
  } catch (error) {
    return NextResponse.json(
      {
        error: String(error instanceof Error ? error.message : error),
        stack: error instanceof Error ? error.stack?.slice(0, 400) : undefined,
      },
      { status: 500 },
    );
  }
}
