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

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

  const leads = await prisma.lead.findMany({
    where: { clinicId: session.id },
    include: {
      appointments: {
        include: { treatment: true },
        orderBy: { dateTime: "desc" },
      },
    },
    orderBy: { createdAt: "desc" },
  });

  return NextResponse.json(leads);
}

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

  const body = await req.json();

  if (!body.name || !body.phone) {
    return NextResponse.json({ error: "Name and phone are required" }, { status: 400 });
  }

  // Check for duplicate phone
  const existing = await prisma.lead.findFirst({
    where: { clinicId: session.id, phone: body.phone },
  });
  if (existing) {
    return NextResponse.json(
      { error: "A lead with this phone number already exists.", existingId: existing.id },
      { status: 409 }
    );
  }

  const lead = await prisma.lead.create({
    data: {
      clinicId: session.id,
      name: body.name,
      phone: body.phone,
      email: body.email || null,
      source: body.source || "manual",
      treatmentInterest: body.treatmentInterest || null,
      notes: body.notes || null,
    },
  });

  return NextResponse.json(lead);
}
