import { waitUntil } from "@vercel/functions";
import { prisma } from "@/lib/prisma";
import { runAudit } from "@/lib/audit/audit-runner";
import { normalizeEmail, normalizePhone } from "@/lib/audit/normalize";

export interface PublicAuditFormData {
  firstName: string;
  lastName: string;
  email: string;
  companyName: string;
  phoneNumber: string;
  websiteUrl: string;
}

export async function createLeadAndTriggerAudit({
  formData,
  ipAddress,
  userAgent,
  bypass,
}: {
  formData: PublicAuditFormData;
  ipAddress: string;
  userAgent: string;
  bypass: boolean;
}): Promise<{ auditId: string; statusUrl: string; leadId: string }> {
  const { firstName, lastName, email, companyName, phoneNumber, websiteUrl } = formData;
  const normEmail = normalizeEmail(email);
  const normPhone = normalizePhone(phoneNumber);
  const emailDomain = email.split("@")[1] ?? "";

  const lead = await prisma.lead.create({
    data: {
      firstName,
      lastName,
      email,
      companyName,
      phoneNumber,
      websiteUrl,
      source: bypass ? "public-audit-bypass" : "public-audit",
      ipAddress,
      userAgent,
      normalizedEmail: normEmail,
      normalizedPhone: normPhone,
      emailVerified: !bypass,
    },
  });

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const audit = await (prisma.audit.create as any)({
    data: {
      brandId: null,
      requesterEmail: email,
      requestedBrandName: companyName,
      requestedWebsite: websiteUrl,
      requestedCompetitors: [],
      requestedLocations: [],
      requestedServices: [],
      isLocal: false,
      auditType: "third-party",
      auditMode: "third-party",
      source: "public",
      status: "queued",
      currentTier: 0,
      totalTiers: 7,
    },
  });

  await prisma.lead.update({
    where: { id: lead.id },
    data: { auditId: audit.id },
  });

  prisma.platformEvent.create({
    data: {
      userId: null, brandId: null,
      action: "public_audit.form_submitted",
      category: "audit",
      metadata: { auditId: audit.id, leadId: lead.id, emailDomain, companyName, source: bypass ? "bypass" : "public-audit", bypass },
      ipAddress,
    },
  }).catch(() => {/* non-fatal */});

  waitUntil(runAudit(audit.id));

  return { auditId: audit.id, statusUrl: `/audit/${audit.id}`, leadId: lead.id };
}
