/** Hosted forms & landing pages (PAGE-001…006): UTM/click-ID capture, spam protection, A/B variants. */
import { and, eq, sql } from "drizzle-orm";
import { schema } from "@/db";
import type { Ctx } from "@/lib/auth";
import { ApiError, rateLimit } from "@/lib/api";
import { emit } from "@/lib/webhooks";
import { isValidPhone, normalizeEmail } from "@/lib/util";
import type { FormSchema, PageSchema } from "@/db/schema";

export type SubmitMeta = {
  utm_source?: string; utm_medium?: string; utm_campaign?: string; utm_term?: string; utm_content?: string;
  fbclid?: string; gclid?: string; landing_url?: string; variant?: string; anonymous_id?: string; fbp?: string;
  ip?: string | null; user_agent?: string | null; captcha_token?: string; hp?: string; started_at?: number;
};

export async function verifyCaptcha(token: string | undefined, ip?: string | null) {
  const secret = process.env.TURNSTILE_SECRET_KEY;
  if (!secret) return true;
  if (!token) return false;
  const r = await fetch("https://challenges.cloudflare.com/turnstile/v0/siteverify", { method: "POST", body: new URLSearchParams({ secret, response: token, ...(ip ? { remoteip: ip } : {}) }) }).then((x) => x.json()).catch(() => ({ success: false }));
  return !!(r as { success?: boolean }).success;
}

export function formSchemaOf(form: typeof schema.forms.$inferSelect): FormSchema | null {
  const s = form.schema as FormSchema | PageSchema;
  return s.kind === "form" ? s : null;
}

export async function submitForm(ctx: Ctx, formId: string, data: Record<string, unknown>, meta: SubmitMeta) {
  const form = await ctx.db.query.forms.findFirst({ where: and(eq(schema.forms.id, formId), eq(schema.forms.workspaceId, ctx.workspace.id)) });
  if (!form) throw new ApiError(404, "not_found", "Form not found");
  let fs = formSchemaOf(form);
  if (!fs && (form.schema as PageSchema).formId) {
    const inner = await ctx.db.query.forms.findFirst({ where: eq(schema.forms.id, (form.schema as PageSchema).formId!) });
    fs = inner ? formSchemaOf(inner) : null;
  }
  if (!fs) throw new ApiError(422, "validation_failed", "This page has no form attached");

  // PAGE-002 spam protection: honeypot, minimum fill time, rate limiting per IP, optional CAPTCHA
  if (meta.hp) return { ok: true, spam: true };
  if (meta.started_at && Date.now() - meta.started_at < 1500) return { ok: true, spam: true };
  const rl = await rateLimit(`form:${form.id}:${meta.ip ?? "unknown"}`, Number(process.env.FORM_RATE_LIMIT_PER_MIN ?? 5));
  if (!rl.ok) throw new ApiError(429, "rate_limited", "Too many submissions — please wait a minute");
  if (fs.captcha && !(await verifyCaptcha(meta.captcha_token, meta.ip))) throw new ApiError(422, "captcha_failed", "CAPTCHA verification failed");

  const errors: Record<string, string> = {};
  const cc = ctx.workspace.settings?.defaultCountryCode ?? (ctx.workspace.currency === "AUD" ? "61" : ctx.workspace.currency === "USD" ? "1" : "880");
  for (const f of fs.fields) {
    const v = data[f.key];
    const empty = v === undefined || v === null || String(v).trim() === "" || v === false;
    if (f.required && empty) errors[f.key] = `${f.label} is required`;
    else if (!empty && f.type === "phone" && !isValidPhone(String(v), cc)) errors[f.key] = "Enter a valid phone number";
    else if (!empty && f.type === "email" && !normalizeEmail(String(v))) errors[f.key] = "Enter a valid email";
    else if (!empty && f.type === "select" && f.options?.length && !f.options.includes(String(v))) errors[f.key] = "Choose a listed option";
  }
  if (Object.keys(errors).length) throw new ApiError(422, "validation_failed", "Please fix the highlighted fields", errors);

  const mapped: Record<string, unknown> = {};
  const custom: Record<string, unknown> = {};
  for (const f of fs.fields) {
    const v = data[f.key];
    if (v === undefined || v === "") continue;
    const target = f.mapTo ?? (["name", "first_name", "last_name", "email", "phone", "city"].includes(f.key) ? f.key : `custom.${f.key}`);
    if (target.startsWith("custom.")) custom[target.slice(7)] = v;
    else mapped[target] = v;
  }
  const consents = (fs.consent ?? []).filter((c) => data[`consent_${c.channel}`]).map((c) => ({ channel: c.channel, status: "opted_in" as const }));
  const { captureLead } = await import("./leads");
  const result = await captureLead(ctx, {
    name: mapped.name as string, firstName: mapped.first_name as string, lastName: mapped.last_name as string, email: mapped.email as string, phone: mapped.phone as string, city: mapped.city as string,
    customFields: custom, project: fs.project, anonymousId: meta.anonymous_id, fbp: meta.fbp, createDeal: fs.createDeal !== false,
    consents, attribution: { channel: "web_form", formId: form.id, utmSource: meta.utm_source, utmMedium: meta.utm_medium, utmCampaign: meta.utm_campaign, utmTerm: meta.utm_term, utmContent: meta.utm_content, fbclid: meta.fbclid, gclid: meta.gclid, landingUrl: meta.landing_url },
  });
  const [sub] = await ctx.db.insert(schema.submissions).values({ workspaceId: ctx.workspace.id, formId: form.id, contactId: result.contact.id, variant: meta.variant ?? null, data, meta: { ...meta, captcha_token: undefined } }).returning();
  await ctx.db.insert(schema.events).values({ workspaceId: ctx.workspace.id, contactId: result.contact.id, name: "form_submit", source: "web", properties: { form: form.name, form_id: form.id, variant: meta.variant ?? null } });
  await bumpFormStat(ctx, form.id, meta.variant ?? "default", "submits");
  await emit(ctx.db, ctx.workspace.id, "form.submitted", { form_id: form.id, submission_id: sub!.id, contact_id: result.contact.id, data });
  const { triggerJourneys, checkGoals } = await import("./journeys");
  await triggerJourneys(ctx, "form_submitted", result.contact.id, { formId: form.id });
  await checkGoals(ctx, result.contact.id, "event_received", "form_submit");
  return { ok: true, contactId: result.contact.id, submissionId: sub!.id, message: fs.successMessage };
}

export async function bumpFormStat(ctx: Pick<Ctx, "db">, formId: string, variant: string, field: "views" | "submits") {
  await ctx.db.execute(sql`UPDATE forms SET stats = COALESCE(stats, '{}'::jsonb) || jsonb_build_object(${variant}::text,
    COALESCE(stats -> ${variant}::text, '{"views":0,"submits":0}'::jsonb) || jsonb_build_object(${field}::text, COALESCE((stats -> ${variant}::text ->> ${field}::text)::int, 0) + 1)) WHERE id = ${formId}`);
}

/** PAGE-005: weighted traffic split, sticky per visitor via cookie. */
export function pickVariant(variants: { key: string; weight: number }[], seed?: string) {
  if (!variants.length) return "default";
  const total = variants.reduce((s, v) => s + Math.max(v.weight, 0), 0) || 1;
  let r = seed ? (parseInt(seed.replace(/[^0-9a-f]/gi, "").slice(0, 8) || "0", 16) % 10000) / 10000 * total : Math.random() * total;
  for (const v of variants) {
    r -= Math.max(v.weight, 0);
    if (r <= 0) return v.key;
  }
  return variants[variants.length - 1]!.key;
}

/** Winner reporting: conversion rate per variant + two-proportion z-test vs control. */
export function abResults(stats: Record<string, { views: number; submits: number }>) {
  const rows = Object.entries(stats).map(([k, s]) => ({ key: k, views: s.views ?? 0, submits: s.submits ?? 0, rate: s.views ? (s.submits / s.views) * 100 : 0 }));
  const control = rows.find((r) => r.key === "default" || r.key === "A") ?? rows[0];
  return rows.map((r) => {
    if (!control || r === control || !r.views || !control.views) return { ...r, lift: null as number | null, confidence: null as number | null };
    const p1 = control.submits / control.views, p2 = r.submits / r.views;
    const p = (control.submits + r.submits) / (control.views + r.views);
    const se = Math.sqrt(p * (1 - p) * (1 / control.views + 1 / r.views));
    const z = se ? (p2 - p1) / se : 0;
    const conf = Math.round((1 - 2 * (1 - normCdf(Math.abs(z)))) * 1000) / 10;
    return { ...r, lift: p1 ? ((p2 - p1) / p1) * 100 : null, confidence: conf };
  });
}

function normCdf(x: number) {
  const t = 1 / (1 + 0.2316419 * x);
  const d = 0.3989423 * Math.exp((-x * x) / 2);
  return 1 - d * t * (0.3193815 + t * (-0.3565638 + t * (1.781478 + t * (-1.821256 + t * 1.330274))));
}
