// GET /api/leads?token=<ADMIN_TOKEN>&format=json|csv
// Renato usa isso pra ver leads capturados a qualquer momento.
import { NextRequest, NextResponse } from "next/server";
import { readLeads } from "@/lib/leads-store";

export const runtime = "nodejs";
export const dynamic = "force-dynamic";

export async function GET(req: NextRequest) {
  const url = new URL(req.url);
  const token = url.searchParams.get("token");
  const format = url.searchParams.get("format") || "json";

  const expected = process.env.ADMIN_TOKEN || "conafor2026renato";
  if (token !== expected) {
    return NextResponse.json({ ok: false, error: "unauthorized" }, { status: 401 });
  }

  const leads = await readLeads();

  if (format === "csv") {
    const header = "timestamp,consultor,nome,empresa,whatsapp,email,ghl_synced";
    const rows = leads.map(
      (l) =>
        `${l.timestamp},${l.consultor},"${l.nome.replace(/"/g, '""')}","${l.empresa.replace(/"/g, '""')}",${l.whatsapp},${l.email},${l.ghl?.synced ?? false}`
    );
    return new Response([header, ...rows].join("\n"), {
      headers: {
        "content-type": "text/csv; charset=utf-8",
        "content-disposition": `attachment; filename="leads-conafor-${new Date().toISOString().slice(0, 10)}.csv"`,
      },
    });
  }

  return NextResponse.json({ ok: true, count: leads.length, leads });
}
