/**
 * Integrations hub. Each provider is a connector behind one interface (connect, sync, push, handleWebhook),
 * so adding a provider never touches module code (BRD §10).
 *
 * Every integration runs in one of two modes:
 *  - live:    real provider APIs with the workspace's encrypted credentials
 *  - sandbox: deterministic simulated responses, so the whole platform can be exercised end-to-end
 *             before Meta app review / Google developer-token approval (BRD §15 risk mitigation).
 */
import { and, eq } from "drizzle-orm";
import { schema } from "@/db";
import type { Ctx } from "@/lib/auth";
import { audit } from "@/lib/audit";
import { emit } from "@/lib/webhooks";
import { uuid, isoDay } from "@/lib/util";
import { logIntegration } from "./http";
import type { Connector, Integration, ProviderMeta } from "./types";
import { metaConnector, loadCreds } from "./meta";
import { googleAdsConnector, ga4Connector, searchConsoleConnector, googleCalendarConnector } from "./google";
import { whatsappConnector, sendgridConnector, sesConnector, twilioSmsConnector, bdSmsConnector } from "./messaging";
import { tiktokConnector, linkedinConnector, stripeConnector, sslcommerzConnector, bkashConnector, slackConnector, zapierConnector, makeConnector, n8nConnector, webhookConnector, anthropicConnector, youtubeConnector, googleBusinessConnector } from "./other";
import { storeAdRows, type AdRow } from "@/lib/services/ads-store";
import { ensureAdAccount } from "./meta";

const ALL: Connector[] = [
  metaConnector, googleAdsConnector, whatsappConnector, webhookConnector, googleCalendarConnector,
  tiktokConnector, linkedinConnector, ga4Connector, searchConsoleConnector,
  sendgridConnector, sesConnector, bdSmsConnector, twilioSmsConnector,
  stripeConnector, sslcommerzConnector, bkashConnector,
  youtubeConnector, googleBusinessConnector,
  slackConnector, zapierConnector, makeConnector, n8nConnector, anthropicConnector,
];

export const CATALOG: ProviderMeta[] = ALL.map((c) => c.meta);
export const getConnector = (key: string) => ALL.find((c) => c.meta.key === key);

export const MESSAGING_PROVIDERS: Record<string, string[]> = {
  whatsapp: ["whatsapp"], email: ["ses", "sendgrid"], sms: ["bd_sms", "twilio"], messenger: ["meta"], instagram: ["meta"],
};

export async function findIntegration(ctx: Pick<Ctx, "db" | "workspace">, providers: string | string[]) {
  const list = Array.isArray(providers) ? providers : [providers];
  const rows = await ctx.db.select().from(schema.integrations).where(and(eq(schema.integrations.workspaceId, ctx.workspace.id), eq(schema.integrations.status, "connected")));
  for (const p of list) {
    const r = rows.find((x) => x.provider === p);
    if (r) return r;
  }
  return null;
}

/** All connected integrations for a set of providers in priority order (used for SMS/email failover). */
export async function findIntegrations(ctx: Pick<Ctx, "db" | "workspace">, providers: string[]) {
  const rows = await ctx.db.select().from(schema.integrations).where(and(eq(schema.integrations.workspaceId, ctx.workspace.id), eq(schema.integrations.status, "connected")));
  return providers.map((p) => rows.find((r) => r.provider === p)).filter(Boolean) as Integration[];
}

export async function pushVia(ctx: Ctx, integration: Integration, op: string, payload: Record<string, unknown>): Promise<Record<string, unknown>> {
  const c = getConnector(integration.provider);
  if (!c?.push) throw new Error(`${integration.provider} does not support ${op}`);
  if (integration.mode === "sandbox") {
    await logIntegration(ctx, integration.provider, integration.id, "out", op, "ok", `[sandbox] ${op} accepted`);
    return sandboxPush(integration.provider, op, payload);
  }
  const creds = await loadCreds(ctx, integration);
  if (!creds) throw new Error(`Credentials missing for ${integration.provider}`);
  try {
    return await c.push(ctx, integration, creds, op, payload);
  } catch (e) {
    await markError(ctx, integration, e);
    throw e;
  }
}

export async function syncIntegration(ctx: Ctx, integration: Integration) {
  const c = getConnector(integration.provider);
  if (!c?.sync) return { ok: true, summary: "Nothing to sync" };
  let result;
  try {
    if (integration.mode === "sandbox") result = await sandboxSync(ctx, integration);
    else {
      let creds = await loadCreds(ctx, integration);
      if (!creds) throw new Error("Credentials missing");
      if (integration.expiresAt && integration.expiresAt.getTime() < Date.now() + 3 * 86400000 && c.refresh) {
        const r = await c.refresh(ctx, integration, creds);
        const { writeSecret } = await import("@/lib/vault");
        await writeSecret(ctx.db, ctx.workspace.id, r.creds, integration.tokenRef);
        await ctx.db.update(schema.integrations).set({ expiresAt: r.expiresAt }).where(eq(schema.integrations.id, integration.id));
        creds = r.creds;
      }
      result = await c.sync(ctx, integration, creds);
    }
    await ctx.db.update(schema.integrations).set({ lastSyncAt: new Date(), lastError: result.ok ? null : result.summary, status: "connected", updatedAt: new Date() }).where(eq(schema.integrations.id, integration.id));
    await logIntegration(ctx, integration.provider, integration.id, "in", "sync", result.ok ? "ok" : "error", result.summary);
    return result;
  } catch (e) {
    await markError(ctx, integration, e);
    throw e;
  }
}

async function markError(ctx: Ctx, integration: Integration, e: unknown) {
  const msg = e instanceof Error ? e.message : String(e);
  const expired = /expired|invalid.*token|OAuthException|401|UNAUTHENTICATED/i.test(msg);
  await ctx.db.update(schema.integrations).set({ status: expired ? "expired" : "error", lastError: msg.slice(0, 500), updatedAt: new Date() }).where(eq(schema.integrations.id, integration.id));
  if (expired) {
    await emit(ctx.db, ctx.workspace.id, "integration.disconnected", { integration_id: integration.id, provider: integration.provider, reason: msg });
    const { notifyAdmins } = await import("@/lib/services/notify");
    await notifyAdmins(ctx, "integration", `${integration.displayName ?? integration.provider} needs to be reconnected`, msg, "/integrations");
  }
  await audit(ctx, "integration.error", "integration", integration.id, undefined, { error: msg });
}

/* ---------------- Sandbox implementations ---------------- */

function sandboxPush(provider: string, op: string, payload: Record<string, unknown>): Record<string, unknown> {
  const fakeId = `${provider}_sbx_${uuid().slice(0, 12)}`;
  switch (op) {
    case "send": return { providerMessageId: fakeId, sandbox: true };
    case "conversion": return { events_received: 1, fbtrace_id: fakeId, sandbox: true };
    case "audience": return { audienceId: payload.audienceId ?? fakeId, count: (payload.members as unknown[])?.length ?? 0, sandbox: true };
    case "publish": return { postId: fakeId, sandbox: true };
    case "post_metrics": {
      const seed = String(payload.postId).length;
      return { reach: 800 + seed * 137, engagement: 60 + seed * 11, likes: 40 + seed * 5, comments: 4 + seed, shares: 2 + (seed % 7) };
    }
    case "event": return { eventId: fakeId, sandbox: true };
    case "checkout": return { url: `/billing/sandbox-checkout?invoice=${payload.invoiceId}`, externalId: fakeId, sandbox: true };
    case "call": return { callSid: fakeId, sandbox: true };
    case "template.submit": return { id: fakeId, status: "approved", sandbox: true };
    default: return { ok: true, id: fakeId, sandbox: true };
  }
}

/** Deterministic pseudo-random so sandbox metrics are stable across re-syncs */
function rand(seed: string) {
  let h = 2166136261;
  for (const ch of seed) h = Math.imul(h ^ ch.charCodeAt(0), 16777619);
  return ((h >>> 0) % 10000) / 10000;
}

/** Industry-neutral sandbox campaigns for workspaces that are not in real estate. */
const NEUTRAL_CAMPAIGNS: Record<string, { name: string; sets: string[] }[]> = {
  meta: [{ name: "Lead Gen – Spring offer", sets: ["Lookalike 1% Customers", "Interest: In-market"] }, { name: "Retargeting – Website visitors", sets: ["Retargeting 30d", "Dhaka 25-55"] }, { name: "Brand Awareness", sets: ["Broad Bangladesh"] }],
  google: [{ name: "Search – Brand & services", sets: ["Brand terms", "Service terms"] }, { name: "PMax – Core offer", sets: ["Asset group A"] }],
  tiktok: [{ name: "TikTok – Lifestyle videos", sets: ["Gen Z Dhaka"] }],
  linkedin: [{ name: "LinkedIn – Decision makers", sets: ["Managers & owners"] }],
};

export const SANDBOX_CAMPAIGNS: Record<string, { name: string; sets: string[] }[]> = {
  meta: [
    { name: "Gulshan Heights – Lead Gen", sets: ["Lookalike 1% Buyers", "Interest: Luxury Apartments"] },
    { name: "Bashundhara Residency – Site Visit", sets: ["Retargeting 30d", "Dhaka 25-55 HHI"] },
    { name: "Brand Awareness – ACE", sets: ["Broad Bangladesh"] },
  ],
  google: [
    { name: "Search – Apartments Dhaka", sets: ["Flat for sale Gulshan", "Apartment Bashundhara"] },
    { name: "PMax – Premium Projects", sets: ["Asset group A"] },
  ],
  tiktok: [{ name: "TikTok – Lifestyle Reels", sets: ["Gen Z Dhaka"] }],
  linkedin: [{ name: "LinkedIn – NRB Investors", sets: ["Expat professionals"] }],
};

async function sandboxSync(ctx: Ctx, integration: Integration) {
  const providerMap: Record<string, string> = { meta: "meta", google_ads: "google", tiktok: "tiktok", linkedin: "linkedin" };
  const provider = providerMap[integration.provider];
  if (integration.provider === "ga4" || integration.provider === "search_console") {
    const daily = Array.from({ length: 30 }, (_, k) => {
      const date = isoDay(-(30 - k));
      const r = rand(integration.provider + date);
      return integration.provider === "ga4"
        ? { date, sessions: Math.round(900 + r * 700), users: Math.round(700 + r * 500), conversions: Math.round(12 + r * 18) }
        : { date, clicks: Math.round(140 + r * 120), impressions: Math.round(5200 + r * 3000), position: Math.round((8 + r * 6) * 10) / 10 };
    });
    await ctx.db.update(schema.integrations).set({ config: { ...integration.config, data: { daily } } }).where(eq(schema.integrations.id, integration.id));
    return { ok: true, summary: `[sandbox] Synced ${daily.length} days`, records: daily.length };
  }
  if (!provider) return { ok: true, summary: "[sandbox] sync complete", records: 0 };
  const account = await ensureAdAccount(ctx, integration, provider, integration.accountRef ?? `${provider}-sandbox`, null);
  const days = Number(integration.config.backfillDays ?? 45);
  const rows: AdRow[] = [];
  const campaigns = (ctx.workspace.settings?.industry ?? "general") === "real_estate" ? SANDBOX_CAMPAIGNS : NEUTRAL_CAMPAIGNS;
  for (const [ci, c] of (campaigns[provider] ?? []).entries()) {
    for (const [si, s] of c.sets.entries()) {
      for (let a = 0; a < 2; a++) {
        const adKey = `${provider}-${ci}-${si}-${a}`;
        for (let d = days; d >= 1; d--) {
          const date = isoDay(-d);
          const r = rand(adKey + date);
          const base = provider === "meta" ? 1 : provider === "google" ? 0.8 : 0.35;
          const spend = Math.round((1800 + r * 2600) * base * 100); // BDT minor units
          const impressions = Math.round(spend / 100 * (9 + r * 6));
          const clicks = Math.round(impressions * (0.009 + r * 0.012));
          const leads = Math.round(clicks * (0.05 + rand(adKey + "l" + date) * 0.07));
          rows.push({
            campaign: { externalId: `${provider}-c${ci}`, name: c.name, objective: ci === 2 ? "awareness" : "leads", budget: 500000 },
            adSet: { externalId: `${provider}-c${ci}-s${si}`, name: s, budget: 250000 },
            ad: { externalId: adKey, name: `${s} · Creative ${String.fromCharCode(65 + a)}` },
            date, spend, impressions, clicks, leads, conversions: Math.round(leads * 0.1),
          });
        }
      }
    }
  }
  await storeAdRows(ctx, account.id, provider, rows);
  return { ok: true, summary: `[sandbox] Synced ${rows.length} ad-day rows`, records: rows.length };
}
