import { NextRequest, NextResponse } from "next/server";
import { CONSULTORES, EVENTO_TAG } from "@/lib/consultores";
import { appendLead, syncToGHL, type Lead } from "@/lib/leads-store";
import crypto from "node:crypto";

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

// Validação básica
function validate(body: any) {
  const errors: Record<string, string> = {};
  if (!body?.nome || typeof body.nome !== "string" || body.nome.trim().length < 2)
    errors.nome = "Nome obrigatório";
  if (!body?.empresa || typeof body.empresa !== "string" || body.empresa.trim().length < 2)
    errors.empresa = "Empresa obrigatória";
  if (!body?.whatsapp || typeof body.whatsapp !== "string") errors.whatsapp = "WhatsApp obrigatório";
  else {
    const digits = body.whatsapp.replace(/\D/g, "");
    if (digits.length < 10 || digits.length > 13)
      errors.whatsapp = "Confira o número. Precisa ter DDD + 9 dígitos.";
  }
  if (!body?.email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(body.email))
    errors.email = "Esse e-mail parece incorreto. Verifique antes de continuar.";
  if (!body?.consultor || !(body.consultor in CONSULTORES))
    errors.consultor = "Consultor inválido";
  return errors;
}

export async function POST(req: NextRequest) {
  let body: any;
  try {
    body = await req.json();
  } catch {
    return NextResponse.json({ ok: false, error: "JSON inválido" }, { status: 400 });
  }

  const errors = validate(body);
  if (Object.keys(errors).length > 0) {
    return NextResponse.json({ ok: false, errors }, { status: 422 });
  }

  const consultor = CONSULTORES[body.consultor as keyof typeof CONSULTORES];

  const lead: Lead = {
    id: crypto.randomUUID(),
    timestamp: new Date().toISOString(),
    consultor: consultor.slug,
    nome: String(body.nome).trim(),
    empresa: String(body.empresa).trim(),
    whatsapp: String(body.whatsapp).replace(/\D/g, ""),
    email: String(body.email).trim().toLowerCase(),
    ghl: { synced: false },
    ip: req.headers.get("x-forwarded-for")?.split(",")[0]?.trim() || undefined,
    userAgent: req.headers.get("user-agent") || undefined,
  };

  // Sync GHL (não bloqueia UX se falhar)
  const ghlResult = await syncToGHL(lead, consultor.ghlTag, EVENTO_TAG);
  lead.ghl = ghlResult;

  try {
    await appendLead(lead);
  } catch (e) {
    // se local falhou mas GHL foi, não é fatal
    console.error("[lead] falha ao persistir local:", e);
  }

  return NextResponse.json({
    ok: true,
    leadId: lead.id,
    ghlSynced: lead.ghl.synced,
  });
}
