/**
 * 🧪 REMINDER TESTING API
 * Lets clinic staff run any active reminder tree against a real phone
 * with all wait-node delays skipped — so the entire sequence fires instantly.
 *
 * GET  ?action=trees                         → list all active trees
 * GET  ?action=status&journeyId=xxx          → journey status + message log
 * POST { action:"run",  treeId, phone }      → start a test run
 * POST { action:"reply", journeyId, message} → simulate a patient reply
 * POST { action:"stop",  journeyId }         → cancel a test journey
 */

import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { getSession } from "@/lib/auth";
import { ReminderTreeEngine } from "@/lib/reminder-tree-engine";

// ─── Auth helper ─────────────────────────────────────────────────
async function auth() {
  const session = await getSession();
  if (!session) return null;
  return session;
}

// ─── GET ─────────────────────────────────────────────────────────
export async function GET(req: NextRequest) {
  const session = await auth();
  if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const { searchParams } = new URL(req.url);
  const action     = searchParams.get("action") || "trees";
  const journeyId  = searchParams.get("journeyId") || "";

  // ── List active trees ─────────────────────────────────────────
  if (action === "trees") {
    const trees = await prisma.reminderTree.findMany({
      where: { clinicId: session.id, isActive: true },
      include: { _count: { select: { nodes: true } } },
      orderBy: { id: "asc" },
    });

    const TRIGGER_LABELS: Record<string, string> = {
      booking_created: "New Booking",
      completed:       "After Appointment",
      no_show:         "No-Show",
      custom:          "Custom",
    };
    const TRIGGER_COLORS: Record<string, string> = {
      booking_created: "emerald",
      completed:       "blue",
      no_show:         "amber",
      custom:          "purple",
    };

    return NextResponse.json({
      trees: trees.map(t => ({
        id:           t.id,
        name:         t.name,
        description:  t.description,
        triggerType:  t.triggerType,
        triggerLabel: TRIGGER_LABELS[t.triggerType] ?? t.triggerType,
        triggerColor: TRIGGER_COLORS[t.triggerType] ?? "gray",
        nodeCount:    t._count.nodes,
      })),
    });
  }

  // ── Journey status + messages ─────────────────────────────────
  if (action === "status" && journeyId) {
    const journey = await prisma.userJourney.findUnique({
      where: { id: journeyId },
      include: {
        currentNode: true,
        tree:        true,
        executions: {
          orderBy: { executedAt: "asc" },
          include: { node: true },
        },
      },
    });
    if (!journey) return NextResponse.json({ error: "Journey not found" }, { status: 404 });

    const messages = await prisma.messageLog.findMany({
      where: { appointmentId: journey.appointmentId },
      orderBy: { sentAt: "asc" },
    });

    return NextResponse.json({
      journey: {
        id:          journey.id,
        status:      journey.status,
        treeName:    journey.tree?.name,
        currentNode: journey.currentNode
          ? { name: journey.currentNode.name, type: journey.currentNode.nodeType }
          : null,
        lastActiveAt: journey.lastActiveAt,
        executions:   journey.executions.map(e => ({
          node:       e.node?.name,
          type:       e.node?.nodeType,
          status:     e.status,
          executedAt: e.executedAt,
        })),
      },
      messages: messages.map(m => ({
        id:        m.id,
        direction: m.direction,
        text:      m.message,
        sentAt:    m.sentAt,
        status:    m.status,
      })),
    });
  }

  return NextResponse.json({ error: "Invalid action" }, { status: 400 });
}

// ─── POST ────────────────────────────────────────────────────────
export async function POST(req: NextRequest) {
  const session = await auth();
  if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const body = await req.json();
  const { action } = body;

  // ── Start a test run ─────────────────────────────────────────
  if (action === "run") {
    const { treeId, phone } = body as { treeId: string; phone: string };
    if (!treeId || !phone) {
      return NextResponse.json({ error: "treeId and phone are required" }, { status: 400 });
    }

    // Verify tree belongs to this clinic
    const tree = await prisma.reminderTree.findFirst({
      where: { id: treeId, clinicId: session.id },
    });
    if (!tree) return NextResponse.json({ error: "Tree not found" }, { status: 404 });

    // Clean phone number
    const cleanPhone = "+" + phone.replace(/\D/g, "");

    // Find or create a test lead
    const last9 = cleanPhone.replace(/\D/g, "").slice(-9);
    let lead = await prisma.lead.findFirst({
      where: { clinicId: session.id, phone: { contains: last9 } },
    });
    if (!lead) {
      lead = await prisma.lead.create({
        data: {
          clinicId: session.id,
          name:     "Test Patient",
          phone:    cleanPhone,
          status:   "new",
        },
      });
    }

    // Find an active treatment
    const treatment = await prisma.treatment.findFirst({
      where: { clinicId: session.id, isActive: true },
    });
    if (!treatment) {
      return NextResponse.json({ error: "No active treatment found. Please create one first." }, { status: 400 });
    }

    // Create a test appointment (3 days in the future)
    const appointment = await prisma.appointment.create({
      data: {
        clinicId:     session.id,
        leadId:       lead.id,
        treatmentId:  treatment.id,
        dateTime:     new Date(Date.now() + 3 * 24 * 60 * 60 * 1000),
        confirmToken: "test-" + Date.now(),
        notes:        "🧪 Test appointment — created by Reminder Testing tool",
      },
    });

    // Start the journey in TEST MODE (all waits skipped)
    const journey = await ReminderTreeEngine.startJourney(
      appointment.id,
      treeId,
      tree.triggerType as any,
      { testMode: true }
    );

    return NextResponse.json({
      journeyId:     journey.id,
      appointmentId: appointment.id,
      treeName:      tree.name,
      phone:         cleanPhone,
    });
  }

  // ── Simulate a patient reply ──────────────────────────────────
  if (action === "reply") {
    const { journeyId, message } = body as { journeyId: string; message: string };
    if (!journeyId || !message) {
      return NextResponse.json({ error: "journeyId and message are required" }, { status: 400 });
    }

    const journey = await prisma.userJourney.findUnique({
      where: { id: journeyId },
      include: { currentNode: true, appointment: true },
    });
    if (!journey) return NextResponse.json({ error: "Journey not found" }, { status: 404 });

    // Log the simulated incoming message
    await prisma.messageLog.create({
      data: {
        clinicId:      journey.appointment.clinicId,
        appointmentId: journey.appointmentId,
        phone:         journey.appointment.leadId, // proxy
        direction:     "incoming",
        message:       message,
        status:        "delivered",
        sentAt:        new Date(),
      },
    });

    await ReminderTreeEngine.handleUserResponse(journey.appointmentId, message);

    const updated = await prisma.userJourney.findUnique({
      where: { id: journeyId },
      include: { currentNode: true },
    });

    return NextResponse.json({
      ok:          true,
      newNode:     updated?.currentNode?.name,
      newNodeType: updated?.currentNode?.nodeType,
      status:      updated?.status,
    });
  }

  // ── Stop / cancel a test journey ─────────────────────────────
  if (action === "stop") {
    const { journeyId } = body as { journeyId: string };
    if (!journeyId) return NextResponse.json({ error: "journeyId required" }, { status: 400 });

    await prisma.userJourney.update({
      where: { id: journeyId },
      data: { status: "paused" },
    });

    return NextResponse.json({ ok: true });
  }

  return NextResponse.json({ error: "Invalid action" }, { status: 400 });
}
