/**
 * Meta: Lead Ads webhooks (leadgen), Marketing API Insights, Conversions API (CAPI incl. CRM/offline events),
 * Custom Audiences, Pages/Instagram publishing, Messenger/Instagram messaging.
 */
import crypto from "node:crypto";
import { and, eq } from "drizzle-orm";
import { schema } from "@/db";
import type { Ctx } from "@/lib/auth";
import { safeEqual } from "@/lib/crypto";
import { isoDay, sha256 } from "@/lib/util";
import { providerFetch } from "./http";
import type { Connector, Credentials, Integration } from "./types";
import { storeAdRows, type AdRow } from "@/lib/services/ads-store";

export const GRAPH = `https://graph.facebook.com/${process.env.META_GRAPH_VERSION ?? "v21.0"}`;

/** Hash PII (SHA-256, normalised) before sending to ad platforms (BRD §10) */
export function hashForAds(v: string | null | undefined, kind: "email" | "phone" | "name") {
  if (!v) return undefined;
  let n = v.trim().toLowerCase();
  if (kind === "phone") n = n.replace(/[^\d]/g, "");
  return sha256(n);
}

export const metaConnector: Connector = {
  meta: {
    key: "meta", name: "Meta (Facebook & Instagram)", category: "ads", priority: "P1",
    description: "Lead Ads capture, Insights metrics, Conversions API, Custom Audiences, Page & Instagram publishing.",
    auth: "oauth", oauthProvider: "meta",
    scopes: ["ads_read", "ads_management", "leads_retrieval", "pages_show_list", "pages_read_engagement", "pages_manage_metadata", "pages_manage_posts", "instagram_basic", "instagram_content_publish", "business_management",
      // Module 11 — comments, private replies, Messenger & Instagram messaging (VERIFY names before app review)
      "pages_read_user_content", "pages_manage_engagement", "pages_messaging", "instagram_manage_comments", "instagram_manage_messages"],
    fields: [
      { key: "adAccountId", label: "Ad account ID (act_…)", placeholder: "act_1234567890" },
      { key: "pixelId", label: "Pixel / Dataset ID for CAPI", placeholder: "1234567890" },
      { key: "pageId", label: "Facebook Page ID", optional: true },
      { key: "igUserId", label: "Instagram business account ID", optional: true },
      { key: "capiToken", label: "CAPI system-user token (optional)", secret: true, optional: true },
    ],
    capabilities: ["Lead capture (real-time)", "Daily ads metrics", "CAPI conversion sync", "Custom audiences", "Post publishing"],
    docs: "https://developers.facebook.com/docs/marketing-api",
  },

  async connect(ctx, creds, config) {
    if (!creds.accessToken) throw new Error("Missing access token");
    const me = await providerFetch<{ id: string; name: string }>(ctx, "meta", null, "me", `${GRAPH}/me?fields=id,name&access_token=${encodeURIComponent(creds.accessToken)}`);
    return { accountRef: String(config.adAccountId ?? me.id), displayName: `${me.name}${config.adAccountId ? ` · ${config.adAccountId}` : ""}` };
  },

  async refresh(ctx, integration, creds) {
    // exchange for a fresh long-lived token (≈60 days)
    const appId = process.env.META_APP_ID, appSecret = process.env.META_APP_SECRET;
    if (!appId || !appSecret || !creds.accessToken) throw new Error("Meta app credentials not configured");
    const r = await providerFetch<{ access_token: string; expires_in?: number }>(ctx, "meta", integration.id, "token.refresh",
      `${GRAPH}/oauth/access_token?grant_type=fb_exchange_token&client_id=${appId}&client_secret=${appSecret}&fb_exchange_token=${encodeURIComponent(creds.accessToken)}`);
    return { creds: { ...creds, accessToken: r.access_token }, expiresAt: r.expires_in ? new Date(Date.now() + r.expires_in * 1000) : null };
  },

  async sync(ctx, integration, creds) {
    const actId = String(integration.config.adAccountId ?? "");
    if (!actId) return { ok: false, summary: "No ad account selected" };
    const account = await ensureAdAccount(ctx, integration, "meta", actId, creds);
    const since = isoDay(-Number(integration.config.backfillDays ?? 3));
    const until = isoDay(-1);
    const fields = "campaign_id,campaign_name,adset_id,adset_name,ad_id,ad_name,spend,impressions,clicks,actions";
    let url: string | null = `${GRAPH}/${actId}/insights?level=ad&time_increment=1&fields=${fields}&time_range=${encodeURIComponent(JSON.stringify({ since, until }))}&limit=500&access_token=${encodeURIComponent(creds.accessToken!)}`;
    const rows: AdRow[] = [];
    while (url) {
      const page: { data: any[]; paging?: { next?: string } } = await providerFetch(ctx, "meta", integration.id, "insights", url);
      for (const r of page.data) {
        const leads = Number((r.actions ?? []).find((a: any) => a.action_type === "lead" || a.action_type === "onsite_conversion.lead_grouped")?.value ?? 0);
        rows.push({
          campaign: { externalId: r.campaign_id, name: r.campaign_name }, adSet: { externalId: r.adset_id, name: r.adset_name }, ad: { externalId: r.ad_id, name: r.ad_name },
          date: r.date_start, spend: Math.round(Number(r.spend ?? 0) * 100), impressions: Number(r.impressions ?? 0), clicks: Number(r.clicks ?? 0), leads, conversions: 0,
        });
      }
      url = page.paging?.next ?? null;
    }
    await storeAdRows(ctx, account.id, "meta", rows);
    return { ok: true, summary: `Synced ${rows.length} ad-day rows (${since} → ${until})`, records: rows.length };
  },

  async push(ctx, integration, creds, op, p) {
    const token = creds.capiToken || creds.accessToken!;
    if (op === "conversion") {
      const pixelId = String(integration.config.pixelId ?? "");
      if (!pixelId) throw new Error("Pixel/Dataset ID not configured on the Meta integration");
      const body = {
        data: [{
          event_name: p.eventName, event_time: Math.floor(new Date(String(p.eventTime ?? Date.now())).getTime() / 1000),
          event_id: p.eventId, action_source: "system_generated",
          user_data: p.userData,
          custom_data: { currency: p.currency, value: p.value, lead_event_source: "Tempest Pulse", event_source: "crm" },
        }],
        ...(process.env.META_TEST_EVENT_CODE ? { test_event_code: process.env.META_TEST_EVENT_CODE } : {}),
      };
      return providerFetch(ctx, "meta", integration.id, "capi.event", `${GRAPH}/${pixelId}/events?access_token=${encodeURIComponent(token)}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
    }
    if (op === "audience") {
      const actId = String(integration.config.adAccountId);
      let audienceId = p.audienceId as string | undefined;
      if (!audienceId) {
        const a = await providerFetch<{ id: string }>(ctx, "meta", integration.id, "audience.create", `${GRAPH}/${actId}/customaudiences?access_token=${encodeURIComponent(token)}`, {
          method: "POST", headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ name: p.name, subtype: "CUSTOM", description: "Synced from Tempest Pulse", customer_file_source: "USER_PROVIDED_ONLY" }),
        });
        audienceId = a.id;
      }
      const members = (p.members as { email?: string; phone?: string }[]).map((m) => [hashForAds(m.email, "email") ?? "", hashForAds(m.phone, "phone") ?? ""]);
      for (let i = 0; i < members.length; i += 10000) {
        await providerFetch(ctx, "meta", integration.id, "audience.users", `${GRAPH}/${audienceId}/usersreplace?access_token=${encodeURIComponent(token)}`, {
          method: "POST", headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ session: { session_id: Date.now(), batch_seq: i / 10000 + 1, last_batch_flag: i + 10000 >= members.length }, payload: { schema: ["EMAIL", "PHONE"], data: members.slice(i, i + 10000) } }),
        });
      }
      return { audienceId, count: members.length };
    }
    if (op === "publish") {
      const pageId = String(integration.config.pageId ?? "");
      if (!pageId) throw new Error("Facebook Page ID not configured");
      const r = await providerFetch<{ id: string }>(ctx, "meta", integration.id, "page.publish", `${GRAPH}/${pageId}/feed`, {
        method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ message: p.body, access_token: creds.pageToken ?? token, link: p.link }),
      });
      return { postId: r.id };
    }
    if (op === "post_metrics") {
      const r = await providerFetch<any>(ctx, "meta", integration.id, "post.metrics", `${GRAPH}/${p.postId}?fields=insights.metric(post_impressions_unique,post_engaged_users),likes.summary(true),comments.summary(true),shares&access_token=${encodeURIComponent(creds.pageToken ?? token)}`);
      const ins = Object.fromEntries((r.insights?.data ?? []).map((m: any) => [m.name, m.values?.[0]?.value ?? 0]));
      return { reach: ins.post_impressions_unique ?? 0, engagement: ins.post_engaged_users ?? 0, likes: r.likes?.summary?.total_count ?? 0, comments: r.comments?.summary?.total_count ?? 0, shares: r.shares?.count ?? 0 };
    }
    if (op === "messenger.send") {
      const pageId = String(integration.config.pageId ?? "me");
      const r = await providerFetch<{ message_id: string }>(ctx, "meta", integration.id, "messenger.send", `${GRAPH}/${pageId}/messages?access_token=${encodeURIComponent(creds.pageToken ?? token)}`, {
        method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ recipient: { id: p.psid }, messaging_type: "RESPONSE", message: { text: p.body } }),
      });
      return { providerMessageId: r.message_id };
    }
    if (op === "ad.status" || op === "ad.budget") {
      const target = String(p.externalId);
      const payload: Record<string, unknown> = op === "ad.status" ? { status: p.status === "paused" ? "PAUSED" : "ACTIVE" } : { daily_budget: Math.round(Number(p.budget)) };
      await providerFetch(ctx, "meta", integration.id, op, `${GRAPH}/${target}?access_token=${encodeURIComponent(token)}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload) });
      return { ok: true };
    }
    throw new Error(`Unsupported Meta operation ${op}`);
  },

  /** X-Hub-Signature-256 = sha256 HMAC of the raw body with the app secret */
  verifyWebhook(raw, headers) {
    const secret = process.env.META_APP_SECRET;
    if (!secret) return process.env.NODE_ENV !== "production";
    const sig = headers.get("x-hub-signature-256") ?? "";
    const expected = "sha256=" + crypto.createHmac("sha256", secret).update(raw).digest("hex");
    return safeEqual(sig, expected);
  },

  async handleWebhook(ctx, integration, body) {
    const { captureLead } = await import("@/lib/services/leads");
    const b = body as { object?: string; entry?: any[] };
    let handled = 0;
    for (const entry of b.entry ?? []) {
      for (const change of entry.changes ?? []) {
        if (change.field !== "leadgen") continue;
        const v = change.value;
        let fields: Record<string, string> = {};
        const creds = integration ? await loadCreds(ctx, integration) : null;
        if (creds?.accessToken && integration?.mode === "live") {
          const lead = await providerFetch<any>(ctx, "meta", integration.id, "lead.fetch", `${GRAPH}/${v.leadgen_id}?fields=field_data,ad_id,adset_id,campaign_id,form_id,created_time&access_token=${encodeURIComponent(creds.pageToken ?? creds.accessToken)}`);
          fields = Object.fromEntries((lead.field_data ?? []).map((f: any) => [f.name, f.values?.[0] ?? ""]));
          v.ad_id ??= lead.ad_id; v.adset_id ??= lead.adset_id; v.campaign_id ??= lead.campaign_id;
        } else if (v.field_data) {
          fields = Object.fromEntries(v.field_data.map((f: any) => [f.name, f.values?.[0] ?? ""]));
        }
        const map = integration?.fieldMapping ?? {};
        const pick = (target: string, ...fallbacks: string[]) => {
          const src = Object.entries(map).find(([, t]) => t === target)?.[0];
          return (src && fields[src]) || fallbacks.map((f) => fields[f]).find(Boolean);
        };
        const custom: Record<string, unknown> = {};
        for (const [src, target] of Object.entries(map)) if (target.startsWith("custom.") && fields[src]) custom[target.slice(7)] = fields[src];
        await captureLead(ctx, {
          name: pick("name", "full_name", "name"), firstName: pick("first_name", "first_name"), lastName: pick("last_name", "last_name"),
          email: pick("email", "email"), phone: pick("phone", "phone_number", "phone"), city: pick("city", "city"),
          customFields: custom,
          attribution: { channel: "meta_lead_ad", campaignId: v.campaign_id, adsetId: v.adset_id, adId: v.ad_id, utmSource: "facebook", utmMedium: "paid_social" },
          externalId: v.leadgen_id,
        });
        handled++;
      }
    }
    // Module 11: page feed comments, Instagram comments/mentions and Messenger/IG DMs
    const { normalizeMeta } = await import("./social");
    const { handleMetaEvents } = await import("@/lib/services/social-accounts");
    handled += await handleMetaEvents(ctx, normalizeMeta(body).filter((e) => e.type === "comment" || e.type === "dm"));
    return { handled };
  },
};

export async function loadCreds(ctx: Pick<Ctx, "db">, integration: Integration): Promise<Credentials | null> {
  if (!integration.tokenRef) return null;
  const { readSecret } = await import("@/lib/vault");
  return readSecret(ctx.db, integration.tokenRef);
}

export async function ensureAdAccount(ctx: Ctx, integration: Integration, provider: string, externalId: string, creds: Credentials | null) {
  const existing = await ctx.db.query.adAccounts.findFirst({ where: and(eq(schema.adAccounts.workspaceId, ctx.workspace.id), eq(schema.adAccounts.provider, provider), eq(schema.adAccounts.externalId, externalId)) });
  if (existing) return existing;
  let name = integration.mode === "sandbox" ? (integration.displayName ?? externalId).replace(/\s*\(sandbox\)$/, "") : externalId, currency = ctx.workspace.currency, timezone = ctx.workspace.timezone;
  if (provider === "meta" && creds?.accessToken && integration.mode === "live") {
    const a = await providerFetch<any>(ctx, "meta", integration.id, "adaccount", `${GRAPH}/${externalId}?fields=name,currency,timezone_name&access_token=${encodeURIComponent(creds.accessToken)}`);
    name = a.name; currency = a.currency; timezone = a.timezone_name;
  }
  const [row] = await ctx.db.insert(schema.adAccounts).values({ workspaceId: ctx.workspace.id, integrationId: integration.id, provider, externalId, name, currency, timezone, pixelId: (integration.config.pixelId as string) ?? null }).returning();
  return row!;
}
