/**
 * 🧪 FLOW TEST RUNNER
 * DEV ONLY — tests reminder tree flows end-to-end.
 *
 * GET  /api/test-flow?flow=1&action=start      — start flow 1
 * GET  /api/test-flow?flow=1&action=reply&msg=1 — simulate patient reply
 * GET  /api/test-flow?action=status            — show all active journeys
 * GET  /api/test-flow?action=reset             — pause all active journeys
 */
import { NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { triggerTree, sendDirectBookingConfirmation } from "@/lib/tree-trigger";
import { ReminderTreeEngine } from "@/lib/reminder-tree-engine";

const CLINIC_ID  = "cmmhz5xtg0000rg8kmlgad0hf"; // buatiy clinic
const LEAD_PHONE = "201066544750";

const FLOWS = [
  { num: 1, trigger: "booking_created" as const, name: "📅 Appointment Reminder (AI)" },
  { num: 2, trigger: "completed"        as const, name: "💊 Post-Treatment Follow-Up"  },
  { num: 3, trigger: "no_show"          as const, name: "😟 No-Show Recovery (AI)"     },
];

export async function GET(req: Request) {
  const { searchParams } = new URL(req.url);
  const action = searchParams.get("action") || "status";
  const flowNum = parseInt(searchParams.get("flow") || "0");
  const msg     = searchParams.get("msg") || "";

  try {
    // ── STATUS ──────────────────────────────────────────────────
    if (action === "status") {
      const journeys = await prisma.userJourney.findMany({
        where: { status: "active" },
        include: {
          currentNode: true,
          tree: true,
          appointment: { include: { lead: true } },
          executions: { orderBy: { executedAt: "desc" }, take: 3, include: { node: true } },
        },
        orderBy: { lastActiveAt: "desc" },
      });
      const logs = await prisma.messageLog.findMany({
        where: { phone: { contains: LEAD_PHONE } },
        orderBy: { createdAt: "desc" },
        take: 10,
      });
      return NextResponse.json({
        activeJourneys: journeys.map(j => ({
          id: j.id,
          tree: j.tree?.name,
          trigger: j.tree?.triggerType,
          currentNode: { type: j.currentNode?.nodeType, name: j.currentNode?.name },
          lastActive: j.lastActiveAt,
          recentExecutions: j.executions.map(e => e.node?.name),
        })),
        recentMessages: logs.map(l => ({
          direction: l.direction,
          status: l.status,
          wahaId: l.wahaMessageId,
          preview: (l.message || "").slice(0, 80),
          time: l.sentAt,
        })),
      });
    }

    // ── RESET ──────────────────────────────────────────────────
    if (action === "reset") {
      const r = await prisma.userJourney.updateMany({
        where: { status: "active" },
        data: { status: "paused" },
      });
      return NextResponse.json({ reset: true, journeysPaused: r.count });
    }

    // ── START FLOW ──────────────────────────────────────────────
    if (action === "start" && flowNum >= 1 && flowNum <= 3) {
      const flow = FLOWS[flowNum - 1];

      // Pause any active journeys first
      await prisma.userJourney.updateMany({
        where: { status: "active" },
        data: { status: "paused" },
      });

      // Get test appointment
      const lead = await prisma.lead.findFirst({
        where: { clinicId: CLINIC_ID, phone: { contains: LEAD_PHONE } },
      });
      if (!lead) return NextResponse.json({ error: "Lead not found" }, { status: 404 });

      let apt = await prisma.appointment.findFirst({
        where: { clinicId: CLINIC_ID, leadId: lead.id },
        orderBy: { createdAt: "desc" },
        include: { lead: true, treatment: true },
      });

      // Create appointment if none
      if (!apt) {
        const tx = await prisma.treatment.findFirst({ where: { clinicId: CLINIC_ID, isActive: true } });
        apt = await prisma.appointment.create({
          data: {
            clinicId: CLINIC_ID,
            leadId: lead.id,
            treatmentId: tx!.id,
            dateTime: new Date(Date.now() + 3 * 24 * 60 * 60 * 1000),
            confirmToken: "test-" + Date.now(),
          },
          include: { lead: true, treatment: true },
        }) as any;
      }

      console.log(`🧪 Starting FLOW ${flowNum}: ${flow.name} for apt ${apt!.id}`);
      const result = await triggerTree(apt!.id, flow.trigger);

      return NextResponse.json({
        flow: flowNum,
        name: flow.name,
        trigger: flow.trigger,
        appointment: apt!.id,
        result,
        next: `Reply on WhatsApp, then call: /api/test-flow?action=reply&msg=YOUR_REPLY`,
      });
    }

    // ── SIMULATE REPLY ─────────────────────────────────────────
    if (action === "reply" && msg) {
      // Find active journey for this phone
      const journey = await prisma.userJourney.findFirst({
        where: {
          status: "active",
          appointment: {
            lead: { phone: { contains: LEAD_PHONE } },
          },
        },
        include: {
          currentNode: true,
          tree: true,
          appointment: { include: { lead: true } },
        },
        orderBy: { lastActiveAt: "desc" },
      });

      if (!journey) {
        return NextResponse.json({ error: "No active journey. Start a flow first." }, { status: 400 });
      }

      const beforeNode = journey.currentNode?.name;
      await ReminderTreeEngine.handleUserResponse(journey.appointmentId, msg);

      // Reload to see new node
      const updated = await prisma.userJourney.findUnique({
        where: { id: journey.id },
        include: { currentNode: true },
      });

      return NextResponse.json({
        replied: msg,
        journey: journey.id,
        tree: journey.tree?.name,
        nodeBefore: beforeNode,
        nodeAfter: updated?.currentNode?.name,
        journeyStatus: updated?.status,
      });
    }

    return NextResponse.json({ error: "Unknown action", availableActions: ["status","reset","start","reply"] }, { status: 400 });

  } catch (err: any) {
    console.error("❌ test-flow error:", err.message);
    return NextResponse.json({ error: err.message }, { status: 500 });
  }
}
