/**
 * Messaging providers: WhatsApp Business Cloud API (MSG-001), Email via SES or SendGrid (MSG-002),
 * SMS via local Bangladesh gateways or Twilio with Bangla Unicode (MSG-003), Messenger/Instagram (MSG-004, via meta.ts).
 */
import crypto from "node:crypto";
import { safeEqual } from "@/lib/crypto";
import { providerFetch } from "./http";
import type { Connector } from "./types";
import { GRAPH } from "./meta";

export const whatsappConnector: Connector = {
  meta: {
    key: "whatsapp", name: "WhatsApp Business (Cloud API)", category: "messaging", priority: "P1",
    description: "Template sends, session replies, media and delivery status; inbound chats thread to the contact.",
    auth: "credentials",
    fields: [
      { key: "phoneNumberId", label: "Phone number ID", placeholder: "1098765432" },
      { key: "wabaId", label: "WhatsApp Business Account ID", placeholder: "2345678901" },
      { key: "accessToken", label: "Permanent access token", secret: true },
      { key: "verifyToken", label: "Webhook verify token", secret: true, optional: true },
    ],
    capabilities: ["Template messages", "Session replies", "Media", "Delivery receipts", "Inbound chat"],
    docs: "https://developers.facebook.com/docs/whatsapp/cloud-api",
  },
  async connect(ctx, creds, config) {
    const pn = await providerFetch<{ display_phone_number: string; verified_name: string }>(ctx, "whatsapp", null, "phone.get", `${GRAPH}/${config.phoneNumberId}?fields=display_phone_number,verified_name&access_token=${encodeURIComponent(creds.accessToken ?? "")}`);
    return { accountRef: String(config.phoneNumberId), displayName: `${pn.verified_name} (${pn.display_phone_number})` };
  },
  async push(ctx, integration, creds, op, p) {
    const pnId = integration.config.phoneNumberId;
    if (op === "send") {
      const to = String(p.to).replace(/^\+/, "");
      const message = p.template
        ? { type: "template", template: { name: p.template, language: { code: p.language ?? "en" }, components: p.components ?? [] } }
        : p.mediaUrl
          ? { type: String(p.mediaType ?? "image"), [String(p.mediaType ?? "image")]: { link: p.mediaUrl, caption: p.body } }
          : { type: "text", text: { body: p.body, preview_url: true } };
      const r = await providerFetch<{ messages: { id: string }[] }>(ctx, "whatsapp", integration.id, "messages.send", `${GRAPH}/${pnId}/messages`, {
        method: "POST", headers: { Authorization: `Bearer ${creds.accessToken}`, "Content-Type": "application/json" },
        body: JSON.stringify({ messaging_product: "whatsapp", recipient_type: "individual", to, ...message }),
      });
      return { providerMessageId: r.messages?.[0]?.id };
    }
    if (op === "template.submit") {
      const r = await providerFetch<{ id: string; status: string }>(ctx, "whatsapp", integration.id, "templates.create", `${GRAPH}/${integration.config.wabaId}/message_templates`, {
        method: "POST", headers: { Authorization: `Bearer ${creds.accessToken}`, "Content-Type": "application/json" },
        body: JSON.stringify({ name: p.name, language: p.language ?? "en", category: String(p.category ?? "MARKETING").toUpperCase(), components: [{ type: "BODY", text: p.body }] }),
      });
      return { id: r.id, status: r.status?.toLowerCase() ?? "pending" };
    }
    if (op === "template.status") {
      const r = await providerFetch<{ data: { name: string; status: string }[] }>(ctx, "whatsapp", integration.id, "templates.list", `${GRAPH}/${integration.config.wabaId}/message_templates?fields=name,status&limit=200&access_token=${encodeURIComponent(creds.accessToken ?? "")}`);
      return { templates: r.data };
    }
    throw new Error(`Unsupported WhatsApp operation ${op}`);
  },
  verifyWebhook(raw, headers) {
    const secret = process.env.META_APP_SECRET;
    if (!secret) return process.env.NODE_ENV !== "production";
    const expected = "sha256=" + crypto.createHmac("sha256", secret).update(raw).digest("hex");
    return safeEqual(headers.get("x-hub-signature-256") ?? "", expected);
  },
  async handleWebhook(ctx, _integration, body) {
    const { receiveMessage, updateMessageStatus } = await import("@/lib/services/messaging");
    let handled = 0;
    for (const entry of (body as any).entry ?? []) for (const ch of entry.changes ?? []) {
      const v = ch.value ?? {};
      const names = Object.fromEntries((v.contacts ?? []).map((c: any) => [c.wa_id, c.profile?.name]));
      for (const m of v.messages ?? []) {
        const text = m.text?.body ?? m.button?.text ?? m.interactive?.button_reply?.title ?? m.interactive?.list_reply?.title ?? (m.image ? "[image]" : m.document ? "[document]" : m.audio ? "[voice note]" : m.location ? `[location ${m.location.latitude},${m.location.longitude}]` : "[message]");
        await receiveMessage(ctx, { channel: "whatsapp", from: `+${m.from}`, name: names[m.from], body: text, providerMessageId: m.id, waId: m.from });
        handled++;
      }
      for (const s of v.statuses ?? []) {
        await updateMessageStatus(ctx, s.id, s.status, s.errors?.[0]?.title);
        handled++;
      }
    }
    return { handled };
  },
};

/* ---------------- Email ---------------- */

export const sendgridConnector: Connector = {
  meta: {
    key: "sendgrid", name: "SendGrid", category: "messaging", priority: "P2",
    description: "Marketing & transactional email with open/click tracking and bounce webhooks.",
    auth: "credentials",
    fields: [{ key: "apiKey", label: "API key", secret: true }, { key: "fromEmail", label: "From email" }, { key: "fromName", label: "From name", optional: true }],
    capabilities: ["Email send", "Open/click tracking", "Bounce suppression"],
  },
  async connect(_ctx, _creds, config) {
    return { accountRef: String(config.fromEmail ?? ""), displayName: `SendGrid · ${config.fromEmail ?? ""}` };
  },
  async push(ctx, integration, creds, op, p) {
    if (op !== "send") throw new Error("Unsupported");
    const r = await fetch("https://api.sendgrid.com/v3/mail/send", {
      method: "POST", headers: { Authorization: `Bearer ${creds.apiKey}`, "Content-Type": "application/json" },
      body: JSON.stringify({
        personalizations: [{ to: [{ email: p.to }], custom_args: { message_id: p.messageId } }],
        from: { email: integration.config.fromEmail, name: integration.config.fromName ?? undefined },
        subject: p.subject, content: [{ type: "text/html", value: p.html }],
        tracking_settings: { click_tracking: { enable: true }, open_tracking: { enable: true } },
        headers: p.unsubscribeUrl ? { "List-Unsubscribe": `<${p.unsubscribeUrl}>` } : undefined,
        attachments: Array.isArray(p.attachments) ? p.attachments : undefined,
      }),
    });
    if (!r.ok) throw new Error(`SendGrid ${r.status}: ${await r.text()}`);
    return { providerMessageId: r.headers.get("x-message-id") ?? undefined };
  },
  async handleWebhook(ctx, _i, body) {
    const { updateMessageStatus, handleBounce } = await import("@/lib/services/messaging");
    let handled = 0;
    for (const e of (Array.isArray(body) ? body : []) as any[]) {
      const id = e.message_id ?? String(e.sg_message_id ?? "").split(".")[0];
      if (e.event === "bounce" || e.event === "dropped") await handleBounce(ctx, e.email, e.type === "blocked" ? "soft" : "hard");
      const map: Record<string, string> = { delivered: "delivered", open: "read", click: "clicked", bounce: "failed", dropped: "failed" };
      if (map[e.event]) await updateMessageStatus(ctx, id, map[e.event]!, e.reason);
      handled++;
    }
    return { handled };
  },
};

export const sesConnector: Connector = {
  meta: {
    key: "ses", name: "Amazon SES", category: "messaging", priority: "P2",
    description: "High-volume email via Amazon SES v2 with SNS bounce/complaint notifications.",
    auth: "credentials",
    fields: [{ key: "accessKeyId", label: "Access key ID" }, { key: "secretAccessKey", label: "Secret access key", secret: true }, { key: "region", label: "Region", placeholder: "ap-southeast-1" }, { key: "fromEmail", label: "From email" }, { key: "configurationSet", label: "Configuration set", optional: true }],
    capabilities: ["Email send", "Bounce & complaint handling"],
  },
  async connect(_ctx, _creds, config) {
    return { accountRef: String(config.fromEmail ?? ""), displayName: `SES ${config.region ?? ""} · ${config.fromEmail ?? ""}` };
  },
  async push(ctx, integration, creds, op, p) {
    if (op !== "send") throw new Error("Unsupported");
    const region = String(integration.config.region ?? creds.region ?? "ap-southeast-1");
    const body = JSON.stringify({
      FromEmailAddress: integration.config.fromEmail, Destination: { ToAddresses: [p.to] },
      Content: { Simple: { Subject: { Data: p.subject, Charset: "UTF-8" }, Body: { Html: { Data: p.html, Charset: "UTF-8" } } } },
      ...(integration.config.configurationSet ? { ConfigurationSetName: integration.config.configurationSet } : {}),
      EmailTags: [{ Name: "message_id", Value: String(p.messageId) }],
    });
    const url = `https://email.${region}.amazonaws.com/v2/email/outbound-emails`;
    const headers = sigv4({ method: "POST", url, body, region, service: "ses", accessKeyId: creds.accessKeyId!, secretAccessKey: creds.secretAccessKey! });
    const r = await providerFetch<{ MessageId: string }>(ctx, "ses", integration.id, "SendEmail", url, { method: "POST", headers, body });
    return { providerMessageId: r.MessageId };
  },
  async handleWebhook(ctx, _i, body) {
    const { handleBounce, updateMessageStatus } = await import("@/lib/services/messaging");
    const b = body as any;
    if (b.Type === "SubscriptionConfirmation" && b.SubscribeURL) {
      await fetch(b.SubscribeURL).catch(() => {});
      return { handled: 1 };
    }
    const msg = typeof b.Message === "string" ? JSON.parse(b.Message) : b;
    const type = msg.eventType ?? msg.notificationType;
    const mid = msg.mail?.messageId;
    if (type === "Bounce") for (const r of msg.bounce?.bouncedRecipients ?? []) await handleBounce(ctx, r.emailAddress, msg.bounce.bounceType === "Permanent" ? "hard" : "soft");
    if (type === "Complaint") for (const r of msg.complaint?.complainedRecipients ?? []) await handleBounce(ctx, r.emailAddress, "complaint");
    const map: Record<string, string> = { Delivery: "delivered", Open: "read", Click: "clicked", Bounce: "failed" };
    if (mid && map[type]) await updateMessageStatus(ctx, mid, map[type]!);
    return { handled: 1 };
  },
};

/** Minimal AWS Signature V4 signer for JSON POST requests. */
export function sigv4(o: { method: string; url: string; body: string; region: string; service: string; accessKeyId: string; secretAccessKey: string }) {
  const u = new URL(o.url);
  const amzDate = new Date().toISOString().replace(/[:-]|\.\d{3}/g, "");
  const day = amzDate.slice(0, 8);
  const hash = (s: string) => crypto.createHash("sha256").update(s, "utf8").digest("hex");
  const hm = (k: crypto.BinaryLike, s: string) => crypto.createHmac("sha256", k).update(s, "utf8").digest();
  const headers: Record<string, string> = { host: u.host, "content-type": "application/json", "x-amz-date": amzDate, "x-amz-content-sha256": hash(o.body) };
  const signed = Object.keys(headers).sort();
  const canonical = [o.method, u.pathname, u.searchParams.toString(), signed.map((k) => `${k}:${headers[k]}\n`).join(""), signed.join(";"), headers["x-amz-content-sha256"]].join("\n");
  const scope = `${day}/${o.region}/${o.service}/aws4_request`;
  const toSign = ["AWS4-HMAC-SHA256", amzDate, scope, hash(canonical)].join("\n");
  const kSigning = hm(hm(hm(hm(`AWS4${o.secretAccessKey}`, day), o.region), o.service), "aws4_request");
  const signature = crypto.createHmac("sha256", kSigning).update(toSign).digest("hex");
  const { host: _h, ...rest } = headers;
  return { ...rest, Authorization: `AWS4-HMAC-SHA256 Credential=${o.accessKeyId}/${scope}, SignedHeaders=${signed.join(";")}, Signature=${signature}` };
}

/* ---------------- SMS ---------------- */

const isUnicode = (s: string) => /[^\x00-\x7F]/.test(s);

export const twilioSmsConnector: Connector = {
  meta: {
    key: "twilio", name: "Twilio (SMS & Voice)", category: "messaging", priority: "P2",
    description: "SMS for US / AU with delivery reports; Voice for click-to-call and call recordings.",
    auth: "credentials",
    fields: [{ key: "accountSid", label: "Account SID" }, { key: "authToken", label: "Auth token", secret: true }, { key: "fromNumber", label: "From number / Messaging Service SID" }, { key: "callerId", label: "Voice caller ID", optional: true }],
    capabilities: ["SMS send", "Delivery reports", "Click-to-call", "Call recordings"],
  },
  async connect(ctx, creds, config) {
    const r = await providerFetch<{ friendly_name: string }>(ctx, "twilio", null, "account.get", `https://api.twilio.com/2010-04-01/Accounts/${config.accountSid}.json`, { headers: { Authorization: `Basic ${Buffer.from(`${config.accountSid}:${creds.authToken}`).toString("base64")}` } });
    return { accountRef: String(config.accountSid), displayName: `Twilio · ${r.friendly_name}` };
  },
  async push(ctx, integration, creds, op, p) {
    const sid = String(integration.config.accountSid);
    const auth = `Basic ${Buffer.from(`${sid}:${creds.authToken}`).toString("base64")}`;
    const from = String(integration.config.fromNumber);
    if (op === "send") {
      const form = new URLSearchParams({ To: String(p.to), Body: String(p.body), StatusCallback: String(p.statusCallback ?? "") });
      if (from.startsWith("MG")) form.set("MessagingServiceSid", from); else form.set("From", from);
      const r = await providerFetch<{ sid: string }>(ctx, "twilio", integration.id, "sms.send", `https://api.twilio.com/2010-04-01/Accounts/${sid}/Messages.json`, { method: "POST", headers: { Authorization: auth, "Content-Type": "application/x-www-form-urlencoded" }, body: form });
      return { providerMessageId: r.sid };
    }
    if (op === "call") {
      const twiml = `<Response><Dial record="record-from-answer-dual" recordingStatusCallback="${p.recordingCallback}">${p.to}</Dial></Response>`;
      const r = await providerFetch<{ sid: string }>(ctx, "twilio", integration.id, "call.create", `https://api.twilio.com/2010-04-01/Accounts/${sid}/Calls.json`, {
        method: "POST", headers: { Authorization: auth, "Content-Type": "application/x-www-form-urlencoded" },
        body: new URLSearchParams({ To: String(p.agentPhone), From: String(integration.config.callerId ?? from), Twiml: twiml, StatusCallback: String(p.statusCallback ?? "") }),
      });
      return { callSid: r.sid };
    }
    throw new Error("Unsupported");
  },
  async handleWebhook(ctx, _i, body) {
    const { updateMessageStatus, receiveMessage } = await import("@/lib/services/messaging");
    const b = body as Record<string, string>;
    if (b.MessageStatus && b.MessageSid) await updateMessageStatus(ctx, b.MessageSid, b.MessageStatus === "undelivered" ? "failed" : b.MessageStatus, b.ErrorCode);
    else if (b.Body && b.From) await receiveMessage(ctx, { channel: "sms", from: b.From, body: b.Body, providerMessageId: b.MessageSid });
    else if (b.RecordingUrl && b.CallSid) {
      const { logCallRecording } = await import("@/lib/services/leads");
      await logCallRecording(ctx, b.CallSid, b.RecordingUrl, Number(b.RecordingDuration ?? 0));
    }
    return { handled: 1 };
  },
};

/**
 * Generic local Bangladesh SMS gateway (e.g. SSL Wireless, BulkSMSBD, Alpha SMS…). Vendor is an open question in the BRD,
 * so the request is configurable: URL with {to} {message} {sender} {apiKey} {type} placeholders. Bangla text is sent as unicode.
 */
export const bdSmsConnector: Connector = {
  meta: {
    key: "bd_sms", name: "Bangladesh SMS gateway", category: "messaging", priority: "P2",
    description: "Local BD SMS with Bangla Unicode and delivery-report webhook. Works with any HTTP gateway.",
    auth: "credentials",
    fields: [
      { key: "endpoint", label: "Send URL template", placeholder: "https://gateway.example/api?api_key={apiKey}&senderid={sender}&number={to}&message={message}&type={type}" },
      { key: "apiKey", label: "API key", secret: true },
      { key: "senderId", label: "Sender ID / masking" },
      { key: "method", label: "HTTP method (GET/POST)", placeholder: "GET", optional: true },
      { key: "successPath", label: "Response field holding message ID", placeholder: "message_id", optional: true },
    ],
    capabilities: ["Bangla Unicode SMS", "Delivery reports", "Failover to Twilio"],
  },
  async connect(_ctx, _c, config) {
    return { accountRef: String(config.senderId ?? ""), displayName: `BD SMS · ${config.senderId ?? ""}` };
  },
  async push(ctx, integration, creds, op, p) {
    if (op !== "send") throw new Error("Unsupported");
    const msg = String(p.body);
    const to = String(p.to).replace(/^\+/, "");
    const fill = (s: string) => s.replace("{to}", encodeURIComponent(to)).replace("{message}", encodeURIComponent(msg)).replace("{sender}", encodeURIComponent(String(integration.config.senderId ?? ""))).replace("{apiKey}", encodeURIComponent(creds.apiKey ?? "")).replace("{type}", isUnicode(msg) ? "unicode" : "text");
    const endpoint = String(integration.config.endpoint ?? "");
    const method = String(integration.config.method ?? "GET").toUpperCase();
    const r = await providerFetch<any>(ctx, "bd_sms", integration.id, "sms.send", method === "GET" ? fill(endpoint) : endpoint.split("?")[0]!, method === "GET" ? {} : {
      method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: fill(endpoint.split("?")[1] ?? ""),
    });
    const path = String(integration.config.successPath ?? "message_id");
    return { providerMessageId: typeof r === "object" ? String(path.split(".").reduce((o: any, k) => o?.[k], r) ?? "") : String(r).slice(0, 64), segments: Math.ceil(msg.length / (isUnicode(msg) ? 67 : 153)) };
  },
  async handleWebhook(ctx, _i, body) {
    const { updateMessageStatus } = await import("@/lib/services/messaging");
    const b = body as Record<string, string>;
    const id = b.message_id ?? b.msgid ?? b.sms_id;
    const st = String(b.status ?? b.dlr_status ?? "").toLowerCase();
    if (id) await updateMessageStatus(ctx, id, /deliver|success/.test(st) ? "delivered" : /fail|reject|undeliv/.test(st) ? "failed" : "sent");
    return { handled: 1 };
  },
};
