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

/**
 * PUBLIC API — No auth required.
 * GET /api/book/{slug} — Returns clinic info + active treatments for the public booking page.
 */
export async function GET(
  _req: Request,
  { params }: { params: Promise<{ slug: string }> }
) {
  const { slug } = await params;

  const clinic = await prisma.clinic.findUnique({
    where: { slug },
    select: {
      id: true,
      name: true,
      slug: true,
      phone: true,
      timezone: true,
      quietHoursStart: true,
      quietHoursEnd: true,
    },
  });

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

  const treatments = await prisma.treatment.findMany({
    where: { clinicId: clinic.id, isActive: true },
    select: {
      id: true,
      name: true,
      duration: true,
      price: true,
    },
    orderBy: { name: "asc" },
  });

  return NextResponse.json({ clinic, treatments });
}

/**
 * PUBLIC API — No auth required.
 * POST /api/book/{slug} — Create a lead + appointment from the public booking page.
 * 
 * Body: { name, phone, treatmentId, dateTime, email?, notes? }
 */
export async function POST(
  req: Request,
  { params }: { params: Promise<{ slug: string }> }
) {
  const { slug } = await params;

  const clinic = await prisma.clinic.findUnique({
    where: { slug },
    select: { id: true, name: true },
  });

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

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

  const { name, phone, treatmentId, dateTime, email, notes } = body as {
    name?: string; phone?: string; treatmentId?: string; dateTime?: string; email?: string; notes?: string;
  };

  if (!name || !phone || !treatmentId || !dateTime) {
    return NextResponse.json({ error: "Name, phone, treatment, and date/time are required" }, { status: 400 });
  }

  const dt = new Date(dateTime as string);
  if (isNaN(dt.getTime())) {
    return NextResponse.json({ error: "Invalid date/time" }, { status: 400 });
  }
  if (dt < new Date()) {
    return NextResponse.json({ error: "Cannot book in the past" }, { status: 400 });
  }

  // Validate work hours
  const fullClinic = await prisma.clinic.findUnique({
    where: { slug },
    select: { quietHoursStart: true, quietHoursEnd: true, timezone: true },
  });
  if (fullClinic) {
    const bookingHour = parseInt(
      new Intl.DateTimeFormat("en-US", {
        timeZone: fullClinic.timezone || "Asia/Riyadh",
        hour: "numeric",
        hour12: false,
      }).format(dt)
    );
    const workStart = fullClinic.quietHoursEnd; // quiet ends = work starts
    const workEnd = fullClinic.quietHoursStart;   // quiet starts = work ends
    if (bookingHour < workStart || bookingHour >= workEnd) {
      return NextResponse.json({ error: `Booking is outside work hours (${workStart}:00 - ${workEnd}:00)` }, { status: 400 });
    }
  }

  // Verify treatment
  const treatment = await prisma.treatment.findFirst({
    where: { id: treatmentId, clinicId: clinic.id, isActive: true },
  });
  if (!treatment) {
    return NextResponse.json({ error: "Treatment not found" }, { status: 404 });
  }

  // Find or create lead (dedup by phone suffix)
  const { getPhoneSuffix, normalizePhone } = await import("@/lib/phone");
  const phoneSuffix = getPhoneSuffix(phone);
  const normalizedPhone = normalizePhone(phone);

  let lead = await prisma.lead.findFirst({
    where: { clinicId: clinic.id, phone: { contains: phoneSuffix } },
  });

  if (!lead) {
    lead = await prisma.lead.create({
      data: {
        clinicId: clinic.id,
        name: name.trim(),
        phone: normalizedPhone.startsWith("+") ? normalizedPhone : `+${normalizedPhone}`,
        email: email?.trim() || null,
        source: "website",
        status: "new",
        notes: notes?.trim() || null,
      },
    });
  } else {
    // Update name if lead was auto-created with "WhatsApp XXXX"
    if (lead.name.startsWith("WhatsApp ")) {
      await prisma.lead.update({
        where: { id: lead.id },
        data: { name: name.trim() },
      });
    }
  }

  // Create appointment
  const { generateConfirmToken } = await import("@/lib/reminders");
  const confirmToken = generateConfirmToken();

  const appointment = await prisma.appointment.create({
    data: {
      clinicId: clinic.id,
      leadId: lead.id,
      treatmentId,
      dateTime: dt,
      confirmToken,
      notes: notes?.trim() || null,
    },
  });

  // Update lead status
  await prisma.lead.update({
    where: { id: lead.id },
    data: { status: "booked" },
  }).catch(() => {});

  // Schedule reminders then immediately process due ones (fires booking_confirmed right away)
  const { scheduleReminders, sendBookingConfirmation, processDueReminders } = await import("@/lib/reminders");
  scheduleReminders(appointment.id)
    .then(() => processDueReminders())
    .catch(console.error);
  sendBookingConfirmation(appointment.id).catch(console.error);

  return NextResponse.json({
    success: true,
    appointmentId: appointment.id,
    message: `Booked! You'll receive a WhatsApp confirmation shortly.`,
  });
}
