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

const ALLOWED_STATUSES = ["NEW", "READ", "RESPONDED", "CLOSED"];

// PUT - update lead (status only for now)
export async function PUT(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const session = await requireAdminSession();
  if (!session) return unauthorized();

  try {
    const { id } = await params;
    const body = await req.json();

    const existing = await db.lead.findUnique({ where: { id } });
    if (!existing) return fail("Lead not found", 404);

    const data: { status?: string } = {};
    if (body.status && ALLOWED_STATUSES.includes(body.status)) {
      data.status = body.status;
    }

    if (Object.keys(data).length === 0) {
      return fail("No valid fields to update");
    }

    const lead = await db.lead.update({ where: { id }, data });
    return ok({ lead });
  } catch (e) {
    console.error(e);
    return fail("Failed to update lead", 500);
  }
}

// DELETE - permanently remove a lead
export async function DELETE(_req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const session = await requireAdminSession();
  if (!session) return unauthorized();

  try {
    const { id } = await params;
    const existing = await db.lead.findUnique({ where: { id } });
    if (!existing) return fail("Lead not found", 404);

    await db.lead.delete({ where: { id } });
    return ok({ ok: true });
  } catch (e) {
    console.error(e);
    return fail("Failed to delete lead", 500);
  }
}
