/**
 * DEV ONLY — test endpoint to trigger the booking tree for the latest appointment.
 * DELETE THIS IN PRODUCTION.
 */
import { NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { triggerTree, sendDirectBookingConfirmation } from "@/lib/tree-trigger";

export async function GET(req: Request) {
  try {
    const { searchParams } = new URL(req.url);
    const aptId = searchParams.get("apt");

    // Use provided appointmentId or fall back to the latest appointment
    const apt = aptId
      ? await prisma.appointment.findUnique({ where: { id: aptId }, include: { lead: true, treatment: true } })
      : await prisma.appointment.findFirst({ orderBy: { createdAt: "desc" }, include: { lead: true, treatment: true } });

    if (!apt) return NextResponse.json({ error: "No appointments" }, { status: 404 });

    // Cancel any existing active journeys so we can re-test
    await prisma.userJourney.updateMany({
      where: { appointmentId: apt.id, status: "active" },
      data: { status: "paused" },
    });

    console.log(`🧪 Test-tree: triggering for ${apt.lead.name} (${apt.lead.phone})`);
    const result = await triggerTree(apt.id, "booking_created");

    return NextResponse.json({
      appointment: { id: apt.id, patient: apt.lead.name, phone: apt.lead.phone },
      treeResult: result,
    });
  } catch (err: any) {
    return NextResponse.json({ error: err.message }, { status: 500 });
  }
}

export async function POST(req: Request) {
  // Direct message test — bypass tree entirely
  try {
    const { phone, message } = await req.json();
    const { sendMessage } = await import("@/lib/waha");
    await sendMessage(phone, message);
    return NextResponse.json({ ok: true, sentTo: phone });
  } catch (err: any) {
    return NextResponse.json({ error: err.message }, { status: 500 });
  }
}
