import { and, eq, gte } from "drizzle-orm";
import { getDb } from "@/db";
import { leads } from "@/db/schema";

const allowedSegments = new Set([
  "empresarios", "comerciais", "transicao", "autolideranca", "empresas-rh",
  "event", "corporate", "partner", "mentorship", "support", "vip", "waitlist",
]);
const allowedJourneys = new Set(["waitlist", "masterclass", "corporate", "partner", "mentorship", "support", "vip"]);
const allowedExperimentIds = new Set(["AB01", "AB02", "AB03", "AB04", "AB05"]);
const allowedExperimentVariants = new Set(["A", "B"]);
const allowedAssignmentMethods = new Set(["deterministic_50_50", "query_override", "persisted"]);
const experimentByRoute: Record<string, string> = {
  "/": "AB01",
  "/diagnostico": "AB02",
  "/empresarios-e-gestores": "AB03",
  "/masterclass": "AB04",
  "/imersao": "AB05",
};

function clean(value: unknown, limit: number) {
  return typeof value === "string" ? value.trim().slice(0, limit) : "";
}

function validEmail(value: string) {
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
}

export async function POST(request: Request) {
  try {
    const payload = (await request.json()) as Record<string, unknown>;
    if (clean(payload.website, 120)) return Response.json({ ok: true }, { status: 202 });

    const fullName = clean(payload.fullName, 120);
    const email = clean(payload.email, 180).toLowerCase();
    const phone = clean(payload.phone, 40);
    const segment = clean(payload.segment, 40);
    const journey = clean(payload.journey, 40) || "waitlist";
    const role = clean(payload.role, 120);
    const company = clean(payload.company, 160);
    const sourcePath = clean(payload.sourcePath, 240) || "/";
    const consentService = payload.consentService === true;
    const consentEmailMarketing = payload.consentEmailMarketing === true;
    const consentWhatsapp = payload.consentWhatsapp === true;
    const consentSms = payload.consentSms === true;
    const experimentId = clean(payload.experimentId, 16);
    const experimentVariant = clean(payload.experimentVariant, 1).toUpperCase();
    const assignmentMethod = clean(payload.assignmentMethod, 32);

    if (!fullName || !validEmail(email) || !allowedSegments.has(segment) || !allowedJourneys.has(journey)) {
      return Response.json({ error: "Revise o nome, o e-mail e o perfil selecionado." }, { status: 400 });
    }
    if (!consentService) {
      return Response.json({ error: "É necessário confirmar que leu a informação sobre o tratamento necessário deste pedido." }, { status: 400 });
    }
    if (consentWhatsapp && !phone) {
      return Response.json({ error: "Indique o telefone para autorizar mensagens por WhatsApp." }, { status: 400 });
    }
    const attributionValues = [experimentId, experimentVariant, assignmentMethod];
    const hasAnyAttribution = attributionValues.some(Boolean);
    const validAttribution = attributionValues.every(Boolean)
      && allowedExperimentIds.has(experimentId)
      && allowedExperimentVariants.has(experimentVariant)
      && allowedAssignmentMethods.has(assignmentMethod)
      && experimentByRoute[sourcePath] === experimentId;
    if (hasAnyAttribution && !validAttribution) {
      return Response.json({ error: "A atribuição da experiência não é válida para esta página." }, { status: 400 });
    }

    const db = getDb();
    const fiveMinutesAgo = new Date(Date.now() - 5 * 60 * 1000).toISOString();
    const recent = await db.select({ id: leads.id }).from(leads)
      .where(and(eq(leads.email, email), gte(leads.createdAt, fiveMinutesAgo))).limit(1);
    if (recent.length > 0) return Response.json({ ok: true, duplicate: true });

    const publicId = crypto.randomUUID();
    const utm = (payload.utm ?? {}) as Record<string, unknown>;
    const details = payload.details && typeof payload.details === "object" ? payload.details : {};
    const detailsJson = JSON.stringify(details).slice(0, 12000);
    await db.insert(leads).values({
      publicId, journey, fullName, email, phone: phone || null, segment, role: role || null, company: company || null,
      consentService, consentEmailMarketing, consentWhatsapp, consentSms, sourcePath,
      utmSource: clean(utm.source, 120) || null, utmMedium: clean(utm.medium, 120) || null,
      utmCampaign: clean(utm.campaign, 160) || null, utmContent: clean(utm.content, 160) || null,
      utmTerm: clean(utm.term, 160) || null, creativeId: clean(payload.creativeId, 120) || null,
      experimentId: experimentId || null, experimentVariant: experimentVariant || null,
      assignmentMethod: assignmentMethod || null,
      detailsJson,
    });
    return Response.json({ ok: true, leadId: publicId }, { status: 201 });
  } catch (error) {
    console.error("lead_capture_failed", error);
    return Response.json({ error: "Não foi possível concluir o registo agora. Tente novamente." }, { status: 500 });
  }
}
