/** TikTok, LinkedIn, payments (Stripe, SSLCommerz, bKash), Slack, automation (Zapier/Make/n8n), generic webhooks, AI. */
import crypto from "node:crypto";
import { isoDay, sha256 } from "@/lib/util";
import { safeEqual } from "@/lib/crypto";
import { providerFetch } from "./http";
import type { Connector } from "./types";
import { storeAdRows, type AdRow } from "@/lib/services/ads-store";
import { ensureAdAccount } from "./meta";

export const tiktokConnector: Connector = {
  meta: {
    key: "tiktok", name: "TikTok for Business", category: "ads", priority: "P2",
    description: "Ads metrics, lead forms and Events API conversions.", auth: "credentials",
    fields: [{ key: "advertiserId", label: "Advertiser ID" }, { key: "accessToken", label: "Access token", secret: true }, { key: "pixelCode", label: "Pixel code (Events API)", optional: true }],
    capabilities: ["Daily ads metrics", "Events API conversions", "Lead forms"],
  },
  async connect(_c, _cr, config) {
    return { accountRef: String(config.advertiserId), displayName: `TikTok advertiser ${config.advertiserId}` };
  },
  async sync(ctx, integration, creds) {
    const adv = String(integration.config.advertiserId);
    const account = await ensureAdAccount(ctx, integration, "tiktok", adv, creds);
    const q = new URLSearchParams({ advertiser_id: adv, report_type: "BASIC", data_level: "AUCTION_AD", dimensions: JSON.stringify(["ad_id", "stat_time_day"]), metrics: JSON.stringify(["spend", "impressions", "clicks", "conversion", "campaign_name", "campaign_id", "adgroup_name", "adgroup_id", "ad_name"]), start_date: isoDay(-3), end_date: isoDay(-1), page_size: "1000" });
    const r = await providerFetch<any>(ctx, "tiktok", integration.id, "report", `https://business-api.tiktok.com/open_api/v1.3/report/integrated/get/?${q}`, { headers: { "Access-Token": creds.accessToken! } });
    const rows: AdRow[] = (r.data?.list ?? []).map((x: any) => ({
      campaign: { externalId: String(x.metrics.campaign_id), name: x.metrics.campaign_name }, adSet: { externalId: String(x.metrics.adgroup_id), name: x.metrics.adgroup_name }, ad: { externalId: String(x.dimensions.ad_id), name: x.metrics.ad_name },
      date: String(x.dimensions.stat_time_day).slice(0, 10), spend: Math.round(Number(x.metrics.spend) * 100), impressions: Number(x.metrics.impressions), clicks: Number(x.metrics.clicks), leads: Number(x.metrics.conversion), conversions: 0,
    }));
    await storeAdRows(ctx, account.id, "tiktok", rows);
    return { ok: true, summary: `Synced ${rows.length} rows`, records: rows.length };
  },
  async push(ctx, integration, creds, op, p) {
    if (op !== "conversion") return { skipped: true };
    return providerFetch(ctx, "tiktok", integration.id, "events", "https://business-api.tiktok.com/open_api/v1.3/event/track/", {
      method: "POST", headers: { "Access-Token": creds.accessToken!, "Content-Type": "application/json" },
      body: JSON.stringify({ event_source: "crm", event_source_id: integration.config.pixelCode, data: [{ event: p.eventName, event_time: Math.floor(Date.now() / 1000), event_id: p.eventId, user: { email: p.email ? sha256(String(p.email).toLowerCase()) : undefined, phone: p.phone ? sha256(String(p.phone)) : undefined }, properties: { value: p.value, currency: p.currency } }] }),
    });
  },
};

export const linkedinConnector: Connector = {
  meta: {
    key: "linkedin", name: "LinkedIn Marketing", category: "ads", priority: "P2",
    description: "B2B metrics, Lead Gen Forms and Conversions API.", auth: "credentials",
    fields: [{ key: "adAccountId", label: "Ad account ID" }, { key: "accessToken", label: "Access token", secret: true }, { key: "conversionRuleId", label: "Conversion rule ID", optional: true }],
    capabilities: ["Ads metrics", "Lead Gen Forms", "Conversions API"],
  },
  async connect(_c, _cr, config) {
    return { accountRef: String(config.adAccountId), displayName: `LinkedIn account ${config.adAccountId}` };
  },
  async sync(ctx, integration, creds) {
    const acc = String(integration.config.adAccountId);
    const account = await ensureAdAccount(ctx, integration, "linkedin", acc, creds);
    const s = new Date(Date.now() - 3 * 86400000), e = new Date(Date.now() - 86400000);
    const url = `https://api.linkedin.com/rest/adAnalytics?q=analytics&pivot=CREATIVE&timeGranularity=DAILY&dateRange=(start:(year:${s.getUTCFullYear()},month:${s.getUTCMonth() + 1},day:${s.getUTCDate()}),end:(year:${e.getUTCFullYear()},month:${e.getUTCMonth() + 1},day:${e.getUTCDate()}))&accounts=List(urn%3Ali%3AsponsoredAccount%3A${acc})&fields=costInLocalCurrency,impressions,clicks,oneClickLeads,dateRange,pivotValues`;
    const r = await providerFetch<any>(ctx, "linkedin", integration.id, "adAnalytics", url, { headers: { Authorization: `Bearer ${creds.accessToken}`, "LinkedIn-Version": "202509", "X-Restli-Protocol-Version": "2.0.0" } });
    const rows: AdRow[] = (r.elements ?? []).map((x: any) => {
      const d = x.dateRange.start; const cr = String(x.pivotValues?.[0] ?? "creative").split(":").pop();
      return { campaign: { externalId: `li-${acc}`, name: "LinkedIn campaigns" }, adSet: { externalId: `li-${acc}-set`, name: "All creatives" }, ad: { externalId: cr!, name: `Creative ${cr}` },
        date: `${d.year}-${String(d.month).padStart(2, "0")}-${String(d.day).padStart(2, "0")}`, spend: Math.round(Number(x.costInLocalCurrency ?? 0) * 100), impressions: x.impressions ?? 0, clicks: x.clicks ?? 0, leads: x.oneClickLeads ?? 0, conversions: 0 };
    });
    await storeAdRows(ctx, account.id, "linkedin", rows);
    return { ok: true, summary: `Synced ${rows.length} rows`, records: rows.length };
  },
  async push(ctx, integration, creds, op, p) {
    if (op !== "conversion" || !integration.config.conversionRuleId) return { skipped: true };
    return providerFetch(ctx, "linkedin", integration.id, "conversionEvents", "https://api.linkedin.com/rest/conversionEvents", {
      method: "POST", headers: { Authorization: `Bearer ${creds.accessToken}`, "LinkedIn-Version": "202509", "Content-Type": "application/json" },
      body: JSON.stringify({ conversion: `urn:lla:llaPartnerConversion:${integration.config.conversionRuleId}`, conversionHappenedAt: Date.now(), eventId: p.eventId, conversionValue: { currencyCode: p.currency, amount: String((Number(p.value ?? 0)) / 100) }, user: { userIds: p.email ? [{ idType: "SHA256_EMAIL", idValue: sha256(String(p.email).toLowerCase()) }] : [] } }),
    });
  },
};

export const stripeConnector: Connector = {
  meta: {
    key: "stripe", name: "Stripe", category: "payments", priority: "P2",
    description: "Subscription billing for US / AU workspaces; payment events as conversions.", auth: "credentials",
    fields: [{ key: "secretKey", label: "Secret key", secret: true }, { key: "webhookSecret", label: "Webhook signing secret", secret: true, optional: true }],
    capabilities: ["Checkout", "Subscriptions", "Payment webhooks"],
  },
  async connect(ctx, creds) {
    const r = await providerFetch<{ id: string; settings?: { dashboard?: { display_name?: string } } }>(ctx, "stripe", null, "account", "https://api.stripe.com/v1/account", { headers: { Authorization: `Bearer ${creds.secretKey}` } });
    return { accountRef: r.id, displayName: `Stripe · ${r.settings?.dashboard?.display_name ?? r.id}` };
  },
  async push(ctx, integration, creds, op, p) {
    if (op !== "checkout") throw new Error("Unsupported");
    const form = new URLSearchParams({ mode: "payment", success_url: String(p.successUrl), cancel_url: String(p.cancelUrl), "line_items[0][price_data][currency]": String(p.currency).toLowerCase(), "line_items[0][price_data][product_data][name]": String(p.description), "line_items[0][price_data][unit_amount]": String(p.amount), "line_items[0][quantity]": "1", "metadata[invoice_id]": String(p.invoiceId) });
    const r = await providerFetch<{ id: string; url: string }>(ctx, "stripe", integration.id, "checkout.create", "https://api.stripe.com/v1/checkout/sessions", { method: "POST", headers: { Authorization: `Bearer ${creds.secretKey}`, "Content-Type": "application/x-www-form-urlencoded" }, body: form, idempotencyKey: `inv-${p.invoiceId}` });
    return { url: r.url, externalId: r.id };
  },
  verifyWebhook(raw, headers, creds) {
    const secret = creds?.webhookSecret ?? process.env.STRIPE_WEBHOOK_SECRET;
    if (!secret) return process.env.NODE_ENV !== "production";
    const sig = headers.get("stripe-signature") ?? "";
    const t = sig.match(/t=(\d+)/)?.[1]; const v1 = sig.match(/v1=([a-f0-9]+)/)?.[1];
    if (!t || !v1) return false;
    return safeEqual(crypto.createHmac("sha256", secret).update(`${t}.${raw}`).digest("hex"), v1);
  },
  async handleWebhook(ctx, _i, body) {
    const b = body as any;
    if (b.type === "checkout.session.completed") {
      const { markInvoicePaid } = await import("@/lib/services/billing");
      await markInvoicePaid(ctx, b.data.object.metadata?.invoice_id, b.data.object.id);
    }
    return { handled: 1 };
  },
};

export const sslcommerzConnector: Connector = {
  meta: {
    key: "sslcommerz", name: "SSLCommerz", category: "payments", priority: "P2",
    description: "Bangladesh card, mobile banking & net banking billing; payment events as conversions.", auth: "credentials",
    fields: [{ key: "storeId", label: "Store ID" }, { key: "storePassword", label: "Store password", secret: true }, { key: "sandbox", label: "Sandbox (true/false)", placeholder: "true", optional: true }],
    capabilities: ["Checkout", "IPN webhooks"],
  },
  async connect(_c, _cr, config) {
    return { accountRef: String(config.storeId), displayName: `SSLCommerz · ${config.storeId}` };
  },
  async push(ctx, integration, creds, op, p) {
    if (op !== "checkout") throw new Error("Unsupported");
    const host = integration.config.sandbox === "false" ? "https://securepay.sslcommerz.com" : "https://sandbox.sslcommerz.com";
    const form = new URLSearchParams({ store_id: String(integration.config.storeId), store_passwd: creds.storePassword ?? "", total_amount: (Number(p.amount) / 100).toFixed(2), currency: String(p.currency), tran_id: String(p.invoiceId), success_url: String(p.successUrl), fail_url: String(p.cancelUrl), cancel_url: String(p.cancelUrl), ipn_url: String(p.ipnUrl), cus_name: String(p.customerName ?? "Customer"), cus_email: String(p.customerEmail ?? "billing@example.com"), cus_phone: String(p.customerPhone ?? "01700000000"), cus_add1: "Dhaka", cus_city: "Dhaka", cus_country: "Bangladesh", shipping_method: "NO", product_name: String(p.description), product_category: "SaaS", product_profile: "non-physical-goods" });
    const r = await providerFetch<{ GatewayPageURL: string; sessionkey: string; status: string; failedreason?: string }>(ctx, "sslcommerz", integration.id, "session.init", `${host}/gwprocess/v4/api.php`, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: form });
    if (r.status !== "SUCCESS") throw new Error(r.failedreason ?? "SSLCommerz init failed");
    return { url: r.GatewayPageURL, externalId: r.sessionkey };
  },
  async handleWebhook(ctx, integration, body) {
    const b = body as Record<string, string>;
    if (b.status === "VALID" || b.status === "VALIDATED") {
      // validate with the order validation API before trusting the IPN
      const { loadCreds } = await import("./meta");
      const creds = integration ? await loadCreds(ctx, integration) : null;
      if (integration && creds) {
        const host = integration.config.sandbox === "false" ? "https://securepay.sslcommerz.com" : "https://sandbox.sslcommerz.com";
        const v = await providerFetch<{ status: string; tran_id: string }>(ctx, "sslcommerz", integration.id, "validate", `${host}/validator/api/validationserverAPI.php?val_id=${encodeURIComponent(b.val_id ?? "")}&store_id=${integration.config.storeId}&store_passwd=${encodeURIComponent(creds.storePassword ?? "")}&format=json`);
        if (v.status !== "VALID" && v.status !== "VALIDATED") return { handled: 0 };
      }
      const { markInvoicePaid } = await import("@/lib/services/billing");
      await markInvoicePaid(ctx, b.tran_id, b.val_id);
    }
    return { handled: 1 };
  },
};

export const bkashConnector: Connector = {
  meta: {
    key: "bkash", name: "bKash (Tokenized Checkout)", category: "payments", priority: "P2",
    description: "bKash payments for Bangladesh billing and as conversion events.", auth: "credentials",
    fields: [{ key: "appKey", label: "App key" }, { key: "appSecret", label: "App secret", secret: true }, { key: "username", label: "Username" }, { key: "password", label: "Password", secret: true }, { key: "sandbox", label: "Sandbox (true/false)", placeholder: "true", optional: true }],
    capabilities: ["Checkout", "Payment callback"],
  },
  async connect(_c, _cr, config) {
    return { accountRef: String(config.appKey), displayName: `bKash · ${config.username ?? config.appKey}` };
  },
  async push(ctx, integration, creds, op, p) {
    if (op !== "checkout") throw new Error("Unsupported");
    const host = integration.config.sandbox === "false" ? "https://tokenized.pay.bka.sh/v1.2.0-beta" : "https://tokenized.sandbox.bka.sh/v1.2.0-beta";
    const tok = await providerFetch<{ id_token: string }>(ctx, "bkash", integration.id, "token.grant", `${host}/tokenized/checkout/token/grant`, { method: "POST", headers: { "Content-Type": "application/json", username: String(integration.config.username), password: creds.password ?? "" }, body: JSON.stringify({ app_key: integration.config.appKey, app_secret: creds.appSecret }) });
    const r = await providerFetch<{ bkashURL: string; paymentID: string }>(ctx, "bkash", integration.id, "payment.create", `${host}/tokenized/checkout/create`, { method: "POST", headers: { "Content-Type": "application/json", Authorization: tok.id_token, "X-APP-Key": String(integration.config.appKey) }, body: JSON.stringify({ mode: "0011", payerReference: String(p.invoiceId), callbackURL: p.ipnUrl, amount: (Number(p.amount) / 100).toFixed(2), currency: "BDT", intent: "sale", merchantInvoiceNumber: String(p.invoiceId) }) });
    return { url: r.bkashURL, externalId: r.paymentID };
  },
  async handleWebhook(ctx, integration, body) {
    const b = body as Record<string, string>;
    if (b.status === "success" && b.paymentID && integration) {
      const { loadCreds } = await import("./meta");
      const creds = await loadCreds(ctx, integration);
      const host = integration.config.sandbox === "false" ? "https://tokenized.pay.bka.sh/v1.2.0-beta" : "https://tokenized.sandbox.bka.sh/v1.2.0-beta";
      const tok = await providerFetch<{ id_token: string }>(ctx, "bkash", integration.id, "token.grant", `${host}/tokenized/checkout/token/grant`, { method: "POST", headers: { "Content-Type": "application/json", username: String(integration.config.username), password: creds?.password ?? "" }, body: JSON.stringify({ app_key: integration.config.appKey, app_secret: creds?.appSecret }) });
      const ex = await providerFetch<{ transactionStatus: string; merchantInvoiceNumber: string; trxID: string }>(ctx, "bkash", integration.id, "payment.execute", `${host}/tokenized/checkout/execute`, { method: "POST", headers: { "Content-Type": "application/json", Authorization: tok.id_token, "X-APP-Key": String(integration.config.appKey) }, body: JSON.stringify({ paymentID: b.paymentID }) });
      if (ex.transactionStatus === "Completed") {
        const { markInvoicePaid } = await import("@/lib/services/billing");
        await markInvoicePaid(ctx, ex.merchantInvoiceNumber, ex.trxID);
      }
    }
    return { handled: 1 };
  },
};

export const slackConnector: Connector = {
  meta: {
    key: "slack", name: "Slack", category: "collaboration", priority: "P2",
    description: "New-lead, SLA and anomaly alerts posted to a channel.", auth: "credentials",
    fields: [{ key: "webhookUrl", label: "Incoming webhook URL", secret: true }],
    capabilities: ["Lead alerts", "SLA escalations", "Anomaly alerts"],
  },
  async connect() {
    return { accountRef: "slack", displayName: "Slack incoming webhook" };
  },
  async push(ctx, integration, creds, op, p) {
    if (op !== "notify") throw new Error("Unsupported");
    await providerFetch(ctx, "slack", integration.id, "notify", creds.webhookUrl!, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ text: `*${p.title}*\n${p.body ?? ""}${p.link ? `\n<${p.link}|Open in Tempest Pulse>` : ""}` }) });
    return { ok: true };
  },
};

const automation = (key: string, name: string): Connector => ({
  meta: {
    key, name, category: "automation", priority: "P2",
    description: `Use ${name} triggers (REST hooks on /v1/webhooks) and actions (/v1/leads, /v1/contacts/upsert, /v1/events) with a scoped API key.`,
    auth: "none", capabilities: ["Triggers: all webhook events", "Actions: create lead, upsert contact, track event, move deal"],
    docs: "/docs/api#automation",
  },
});
export const zapierConnector = automation("zapier", "Zapier");
export const makeConnector = automation("make", "Make");
export const n8nConnector = automation("n8n", "n8n");

export const webhookConnector: Connector = {
  meta: {
    key: "webhook", name: "Generic inbound webhook", category: "forms", priority: "P1",
    description: "Any external tool can POST leads to your unique URL (INT-003). Optional HMAC signature verification.",
    auth: "none", capabilities: ["Lead capture from any tool"],
  },
};

export const anthropicConnector: Connector = {
  meta: {
    key: "anthropic", name: "Anthropic Claude", category: "ai", priority: "P2",
    description: "LLM provider behind the internal AI gateway. Platform default uses ANTHROPIC_API_KEY; a workspace can bring its own key.",
    auth: "credentials", fields: [{ key: "apiKey", label: "API key (optional – overrides platform key)", secret: true, optional: true }],
    capabilities: ["Content generation", "Qualification agent", "Ask-your-data", "Summaries", "Recommendations"],
  },
  async connect() {
    return { accountRef: "anthropic", displayName: "Anthropic Claude" };
  },
};

/* Module 11 — social inbox connectors (comments/reviews logic lives in ./social.ts) */
export const youtubeConnector: Connector = {
  meta: {
    key: "youtube", name: "YouTube", category: "messaging", priority: "P2",
    description: "Ingest video comments (adaptive polling within API quota), reply and moderate (hold / reject).",
    auth: "oauth", oauthProvider: "google", scopes: ["https://www.googleapis.com/auth/youtube.force-ssl"],
    fields: [{ key: "channelId", label: "Channel ID (optional — detected on connect)", optional: true }],
    capabilities: ["Comment inbox", "Reply", "Moderation"],
  },
  async connect(_c, _cr, config) {
    return { accountRef: String(config.channelId ?? "youtube"), displayName: "YouTube channel" };
  },
};

export const googleBusinessConnector: Connector = {
  meta: {
    key: "google_business", name: "Google Business Profile", category: "messaging", priority: "P2",
    description: "Reviews per location in the inbox, owner replies, alerts on low ratings.",
    auth: "oauth", oauthProvider: "google", scopes: ["https://www.googleapis.com/auth/business.manage"],
    capabilities: ["Review inbox", "Reply to reviews", "Low-rating alerts"],
  },
  async connect() {
    return { accountRef: "google_business", displayName: "Google Business Profile" };
  },
};
