import { NextResponse } from "next/server";
import { prisma } from "@/lib/db";

/**
 * POST /api/confirm/{id}/action — Confirm an appointment via token.
 * Public endpoint — no auth required, but requires valid token.
 * 
 * Body: { token: string }
 */
export async function POST(
  req: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  const { id } = await params;

  let body: { token?: string };
  try {
    body = await req.json();
  } catch {
    return NextResponse.json({ error: "Invalid request" }, { status: 400 });
  }

  const { token } = body;
  if (!token) {
    return NextResponse.json({ error: "Token required" }, { status: 400 });
  }

  const appointment = await prisma.appointment.findUnique({
    where: { id },
  });

  if (!appointment) {
    return NextResponse.json({ error: "Appointment not found" }, { status: 404 });
  }

  // Validate token
  if (appointment.confirmToken !== token) {
    return NextResponse.json({ error: "Invalid token" }, { status: 403 });
  }

  // Token expiry: only valid within 48 hours of appointment time
  const appointmentTime = new Date(appointment.dateTime);
  const now = new Date();
  const hoursSinceAppointment = (now.getTime() - appointmentTime.getTime()) / (1000 * 60 * 60);

  // Reject if appointment was more than 48h ago, or more than 7 days in the future (link too early)
  if (hoursSinceAppointment > 48) {
    return NextResponse.json({ error: "This confirmation link has expired." }, { status: 410 });
  }

  // Only confirm if in a confirmable state
  if (!["scheduled", "booked"].includes(appointment.status)) {
    return NextResponse.json({ error: `Cannot confirm — appointment is ${appointment.status}` }, { status: 400 });
  }

  // Confirm
  await prisma.appointment.update({
    where: { id },
    data: { status: "confirmed", confirmedAt: new Date() },
  });

  // Update lead status
  try {
    await prisma.lead.update({
      where: { id: appointment.leadId },
      data: { status: "confirmed" },
    });
  } catch { /* non-critical */ }

  // Skip 30-min reminder (they're committed now)
  try {
    await prisma.scheduledReminder.updateMany({
      where: {
        appointmentId: id,
        status: "pending",
        template: { trigger: "30_min_before" },
      },
      data: { status: "skipped" },
    });
  } catch { /* non-critical */ }

  console.log(`✅ Appointment ${id} confirmed via link`);

  return NextResponse.json({ success: true, status: "confirmed" });
}
