import { NextRequest } from "next/server";
import { db } from "@/lib/db";
import { requireAdminSession, unauthorized, ok, fail } from "@/lib/admin-api";

const ALLOWED_TYPES = ["CONTACT", "QUOTE", "CALLBACK", "SERVICE", "EMERGENCY"];
const ALLOWED_STATUSES = ["NEW", "READ", "RESPONDED", "CLOSED"];

// GET - list all leads, optional filters: ?type=QUOTE&status=NEW
export async function GET(req: NextRequest) {
  const session = await requireAdminSession();
  if (!session) return unauthorized();

  try {
    const { searchParams } = new URL(req.url);
    const type = searchParams.get("type");
    const status = searchParams.get("status");

    const where: { type?: string; status?: string } = {};
    if (type && ALLOWED_TYPES.includes(type)) where.type = type;
    if (status && ALLOWED_STATUSES.includes(status)) where.status = status;

    const leads = await db.lead.findMany({
      where,
      orderBy: { createdAt: "desc" },
    });

    return ok({ leads, count: leads.length });
  } catch (e) {
    console.error(e);
    return fail("Failed to fetch leads", 500);
  }
}
