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

/**
 * PUT /api/leads/[id]  — update lead info (name, phone, email, notes, source, status)
 * DELETE /api/leads/[id] — delete a lead (and cascade appointments)
 */
export async function PUT(
  req: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  const session = await getSession();
  if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const { id } = await params;

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

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

  const updateData: Record<string, unknown> = {};

  if (body.name !== undefined && typeof body.name === "string" && body.name.trim()) {
    updateData.name = body.name.toString().trim();
  }
  if (body.phone !== undefined && typeof body.phone === "string" && body.phone.trim()) {
    updateData.phone = body.phone.toString().trim();
  }
  if (body.email !== undefined) {
    updateData.email = typeof body.email === "string" && body.email.trim() ? body.email.toString().trim() : null;
  }
  if (body.source !== undefined && typeof body.source === "string") {
    const validSources = ["manual", "whatsapp", "instagram", "google", "website", "referral", "walk_in"];
    if (validSources.includes(body.source)) {
      updateData.source = body.source;
    }
  }
  if (body.status !== undefined && typeof body.status === "string") {
    const validStatuses = ["new", "contacted", "booked", "confirmed", "arrived", "completed", "no_show", "cancelled", "lost"];
    if (validStatuses.includes(body.status)) {
      updateData.status = body.status;
    }
  }
  if (body.treatmentInterest !== undefined) {
    updateData.treatmentInterest = typeof body.treatmentInterest === "string" ? body.treatmentInterest.trim() : null;
  }
  if (body.notes !== undefined) {
    updateData.notes = typeof body.notes === "string" ? body.notes.trim() : null;
  }

  if (Object.keys(updateData).length === 0) {
    return NextResponse.json({ error: "No valid fields to update" }, { status: 400 });
  }

  const lead = await prisma.lead.update({
    where: { id },
    data: updateData,
  });

  return NextResponse.json(lead);
}

export async function DELETE(
  _req: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  const session = await getSession();
  if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const { id } = await params;

  const existing = await prisma.lead.findFirst({
    where: { id, clinicId: session.id },
  });
  if (!existing) {
    return NextResponse.json({ error: "Lead not found" }, { status: 404 });
  }

  // Delete lead (cascades to appointments → reminders)
  await prisma.lead.delete({ where: { id } });

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