/**
 * Conversion sync (ADS-003, LEAD-008): Lead, Qualified, Site Visit and Won events go back to Meta (CAPI) and
 * Google (offline conversion import), plus TikTok / LinkedIn when connected, with SHA-256 hashed identifiers.
 * One row per (provider, event_id) gives idempotency and the audit trail in ConversionSync.
 */
import { and, desc, eq } from "drizzle-orm";
import { schema } from "@/db";
import type { Ctx } from "@/lib/auth";
import { enqueue } from "@/lib/jobs";
import { emit } from "@/lib/webhooks";
import { hashForAds } from "@/connectors/meta";
import { pushVia } from "@/connectors";

const AD_PROVIDERS = ["meta", "google_ads", "tiktok", "linkedin"];

export async function queueConversions(ctx: Ctx, p: { dealId?: string | null; contactId: string; eventName: string; value?: number; providers?: string[] }) {
  const ws = ctx.workspace.id;
  const integrations = await ctx.db.select().from(schema.integrations).where(and(eq(schema.integrations.workspaceId, ws), eq(schema.integrations.status, "connected")));
  const targets = integrations.filter((i) => (p.providers ?? AD_PROVIDERS).includes(i.provider) && AD_PROVIDERS.includes(i.provider));
  const created: string[] = [];
  for (const i of targets) {
    const eventId = `${p.dealId ?? p.contactId}:${p.eventName}`;
    const [row] = await ctx.db.insert(schema.conversionSyncs).values({
      workspaceId: ws, dealId: p.dealId ?? null, contactId: p.contactId, provider: i.provider === "google_ads" ? "google" : i.provider,
      eventName: p.eventName, eventId, value: p.value ?? 0, currency: ctx.workspace.currency,
    }).onConflictDoNothing().returning({ id: schema.conversionSyncs.id });
    if (row) {
      await enqueue(ctx.db, "conversion.send", { workspaceId: ws, conversionId: row.id, integrationId: i.id }, { workspaceId: ws });
      created.push(row.id);
    }
  }
  return created;
}

export async function sendConversion(ctx: Ctx, conversionId: string, integrationId: string) {
  const conv = await ctx.db.query.conversionSyncs.findFirst({ where: eq(schema.conversionSyncs.id, conversionId) });
  if (!conv || conv.status === "sent") return;
  const integration = await ctx.db.query.integrations.findFirst({ where: eq(schema.integrations.id, integrationId) });
  if (!integration || integration.status !== "connected") {
    await ctx.db.update(schema.conversionSyncs).set({ status: "skipped", response: { reason: "integration not connected" } }).where(eq(schema.conversionSyncs.id, conv.id));
    return;
  }
  const contact = conv.contactId ? await ctx.db.query.contacts.findFirst({ where: eq(schema.contacts.id, conv.contactId) }) : null;
  const src = conv.contactId ? (await ctx.db.select().from(schema.leadSources).where(eq(schema.leadSources.contactId, conv.contactId)).orderBy(desc(schema.leadSources.capturedAt)).limit(5)) : [];
  const fbclid = src.find((s) => s.fbclid)?.fbclid;
  const gclid = src.find((s) => s.gclid)?.gclid;
  const fbp = contact ? (await ctx.db.query.identities.findFirst({ where: and(eq(schema.identities.contactId, contact.id), eq(schema.identities.type, "fbp")) }))?.valueNormalized : undefined;
  const email = contact?.emails[0], phone = contact?.phones[0];
  const userData = {
    em: email ? [hashForAds(email, "email")] : undefined, ph: phone ? [hashForAds(phone, "phone")] : undefined,
    fn: contact?.firstName ? [hashForAds(contact.firstName, "name")] : undefined, ln: contact?.lastName ? [hashForAds(contact.lastName, "name")] : undefined,
    ct: contact?.city ? [hashForAds(contact.city.replace(/\s/g, ""), "name")] : undefined, country: [hashForAds(ctx.workspace.currency === "BDT" ? "bd" : ctx.workspace.currency === "AUD" ? "au" : "us", "name")],
    external_id: contact ? [hashForAds(contact.id, "name")] : undefined,
    fbc: fbclid ? `fb.1.${(src.find((s) => s.fbclid)?.capturedAt ?? new Date()).getTime()}.${fbclid}` : undefined, fbp,
    lead_id: src.find((s) => s.channel === "meta_lead_ad") ? undefined : undefined,
  };
  const payload = { eventName: conv.eventName, eventId: conv.eventId, eventTime: new Date().toISOString(), value: (conv.value ?? 0) / 100, currency: conv.currency, userData, gclid, email, phone };
  try {
    const response = await pushVia(ctx, integration, "conversion", payload);
    const skipped = (response as { skipped?: boolean }).skipped;
    await ctx.db.update(schema.conversionSyncs).set({ status: skipped ? "skipped" : "sent", sentAt: new Date(), payload: { ...payload, email: undefined, phone: undefined }, response, updatedAt: new Date() }).where(eq(schema.conversionSyncs.id, conv.id));
    if (!skipped) {
      if (conv.contactId) await ctx.db.insert(schema.events).values({ workspaceId: ctx.workspace.id, contactId: conv.contactId, name: "conversion.sent", source: "system", properties: { event: conv.eventName, provider: conv.provider } });
      await emit(ctx.db, ctx.workspace.id, "conversion.sent", { conversion_id: conv.id, provider: conv.provider, event: conv.eventName, deal_id: conv.dealId });
    }
  } catch (e) {
    const msg = e instanceof Error ? e.message : String(e);
    await ctx.db.update(schema.conversionSyncs).set({ status: "failed", response: { error: msg }, updatedAt: new Date() }).where(eq(schema.conversionSyncs.id, conv.id));
    await emit(ctx.db, ctx.workspace.id, "conversion.failed", { conversion_id: conv.id, provider: conv.provider, event: conv.eventName, error: msg });
    throw e;
  }
}
