/**
 * Social connectors for Module 11 (SOC). All platform calls go through here, never from module code.
 *
 * VERIFY: every endpoint, permission and messaging window below was written against the providers' documentation at
 * build time; re-check before enabling live mode — platform APIs change. Differences are configured, not hard-coded,
 * where practical (e.g. META_PRIVATE_REPLY_DAYS).
 *
 * Each provider implements: discover (list pages/accounts/channels/locations), subscribe/unsubscribe (webhooks),
 * backfill/poll (pull objects + comments/reviews), act (reply, private reply, hide, unhide, delete, like, review reply),
 * mapAds (ad → effective post). In sandbox mode the same calls return realistic simulated data.
 */
import type { Ctx } from "@/lib/auth";
import type { schema } from "@/db";
import { isoDay, sha256 } from "@/lib/util";
import { providerFetch } from "./http";
import { GRAPH, loadCreds } from "./meta";
import { googleAccessToken } from "./google";
import type { Integration } from "./types";

export type SocialAccountRow = typeof schema.socialAccounts.$inferSelect;
export type Platform = "facebook" | "instagram" | "tiktok" | "linkedin" | "youtube" | "google_business";

export const CHANNEL_FOR: Record<Platform, string> = {
  facebook: "facebook_comment", instagram: "instagram_comment", tiktok: "tiktok", linkedin: "linkedin", youtube: "youtube", google_business: "google_review",
};
export const PLATFORM_FOR_CHANNEL: Record<string, Platform> = Object.fromEntries(Object.entries(CHANNEL_FOR).map(([p, c]) => [c, p as Platform]));
export const IDENTITY_TYPE: Record<Platform, string> = {
  facebook: "fb_psid", instagram: "ig_scoped_id", tiktok: "tiktok_open_id", linkedin: "linkedin_urn", youtube: "youtube_channel_id", google_business: "google_reviewer",
};

/** Capability matrix (§3). UI buttons are driven by these flags. */
export const CAPABILITIES: Record<Platform, schema_SocialCaps> = {
  facebook: { can_reply: true, can_hide: true, can_delete: true, can_like: true, can_private_reply: true, can_dm: true },
  instagram: { can_reply: true, can_hide: true, can_delete: true, can_like: false, can_private_reply: true, can_dm: true },
  youtube: { can_reply: true, can_hide: true, can_delete: true, can_like: false, can_private_reply: false, can_dm: false },
  google_business: { can_reply_review: true },
  tiktok: { can_reply: true, can_hide: true, can_delete: true, can_like: false, can_private_reply: false, can_dm: false },
  linkedin: { can_reply: true, can_hide: false, can_delete: true, can_like: false, can_private_reply: false, can_dm: false },
};
type schema_SocialCaps = { can_reply?: boolean; can_hide?: boolean; can_delete?: boolean; can_like?: boolean; can_private_reply?: boolean; can_dm?: boolean; can_reply_review?: boolean };

/** Meta private replies to a comment are allowed for a limited time after the comment. VERIFY current limit. */
export const PRIVATE_REPLY_DAYS = Number(process.env.META_PRIVATE_REPLY_DAYS ?? 7);

export type DiscoveredAccount = { platform: Platform; channelFamily: string; externalAccountId: string; name: string; avatarUrl?: string; pageToken?: string };
export type NormObject = { externalId: string; type: string; permalink?: string; thumbnailUrl?: string; caption?: string; publishedAt?: string; externalAdId?: string; campaignName?: string };
export type NormComment = {
  platform: Platform; accountExternalId: string; object: NormObject; commentId: string; parentId?: string | null;
  authorId?: string; authorName?: string; authorHandle?: string; body: string; createdAt?: string;
  verb?: "add" | "edited" | "remove" | "hide" | "unhide"; isMention?: boolean;
};
export type NormReview = { accountExternalId: string; reviewId: string; reviewerName?: string; rating: number; body?: string; createdAt?: string; replyBody?: string | null };
export type PullResult = { comments: NormComment[]; reviews: NormReview[]; cursor?: string; quotaUsed?: number };

const sandbox = (i: Integration | null) => !i || i.mode === "sandbox";
const fakeId = (p: string) => `${p}_${sha256(String(Date.now() + Math.random())).slice(0, 14)}`;

/* ------------------------------------------------------------------ */
/* Discovery (SOC-001)                                                  */
/* ------------------------------------------------------------------ */

export async function discoverAccounts(ctx: Ctx, integration: Integration): Promise<DiscoveredAccount[]> {
  const p = integration.provider;
  if (sandbox(integration)) {
    const n = ctx.workspace.name;
    if (p === "meta") return [
      { platform: "facebook", channelFamily: "meta", externalAccountId: `sbx_page_${ctx.workspace.slug}`, name: `${n} (Facebook Page)` },
      { platform: "instagram", channelFamily: "meta", externalAccountId: `sbx_ig_${ctx.workspace.slug}`, name: `@${ctx.workspace.slug.replace(/-/g, "")}` },
    ];
    if (p === "youtube") return [{ platform: "youtube", channelFamily: "youtube", externalAccountId: `sbx_yt_${ctx.workspace.slug}`, name: `${n} (YouTube)` }];
    if (p === "google_business") return [{ platform: "google_business", channelFamily: "google_business", externalAccountId: `sbx_gbp_${ctx.workspace.slug}`, name: `${n} — Head office (Google)` }];
    if (p === "tiktok") return [{ platform: "tiktok", channelFamily: "tiktok", externalAccountId: `sbx_tt_${ctx.workspace.slug}`, name: `${n} (TikTok)` }];
    if (p === "linkedin") return [{ platform: "linkedin", channelFamily: "linkedin", externalAccountId: `sbx_li_${ctx.workspace.slug}`, name: `${n} (LinkedIn)` }];
    return [];
  }
  const creds = await loadCreds(ctx, integration);
  if (!creds) throw new Error("Credentials missing");
  if (p === "meta") {
    // VERIFY: /me/accounts returns Pages with page access tokens and the linked Instagram professional account
    const r = await providerFetch<{ data: any[] }>(ctx, "meta", integration.id, "me.accounts", `${GRAPH}/me/accounts?fields=id,name,access_token,picture{url},instagram_business_account{id,username,profile_picture_url}&limit=100&access_token=${encodeURIComponent(creds.accessToken!)}`);
    const out: DiscoveredAccount[] = [];
    for (const pg of r.data ?? []) {
      out.push({ platform: "facebook", channelFamily: "meta", externalAccountId: pg.id, name: pg.name, avatarUrl: pg.picture?.data?.url, pageToken: pg.access_token });
      if (pg.instagram_business_account) out.push({ platform: "instagram", channelFamily: "meta", externalAccountId: pg.instagram_business_account.id, name: `@${pg.instagram_business_account.username}`, avatarUrl: pg.instagram_business_account.profile_picture_url, pageToken: pg.access_token });
    }
    return out;
  }
  if (p === "youtube") {
    const token = await googleAccessToken(ctx, integration, creds);
    const r = await providerFetch<{ items: any[] }>(ctx, "youtube", integration.id, "channels.mine", "https://www.googleapis.com/youtube/v3/channels?part=snippet&mine=true", { headers: { Authorization: `Bearer ${token}` } });
    return (r.items ?? []).map((c) => ({ platform: "youtube" as const, channelFamily: "youtube", externalAccountId: c.id, name: c.snippet.title, avatarUrl: c.snippet.thumbnails?.default?.url }));
  }
  if (p === "google_business") {
    // VERIFY: Account Management + Business Information APIs; reviews still use the v4 mybusiness endpoint
    const token = await googleAccessToken(ctx, integration, creds);
    const accts = await providerFetch<{ accounts: any[] }>(ctx, "google_business", integration.id, "accounts.list", "https://mybusinessaccountmanagement.googleapis.com/v1/accounts", { headers: { Authorization: `Bearer ${token}` } });
    const out: DiscoveredAccount[] = [];
    for (const a of accts.accounts ?? []) {
      const locs = await providerFetch<{ locations: any[] }>(ctx, "google_business", integration.id, "locations.list", `https://mybusinessbusinessinformation.googleapis.com/v1/${a.name}/locations?readMask=name,title`, { headers: { Authorization: `Bearer ${token}` } });
      for (const l of locs.locations ?? []) out.push({ platform: "google_business", channelFamily: "google_business", externalAccountId: `${a.name}/${l.name}`, name: l.title });
    }
    return out;
  }
  if (p === "tiktok") return [{ platform: "tiktok", channelFamily: "tiktok", externalAccountId: String(integration.config.businessId ?? integration.config.advertiserId), name: `TikTok ${integration.config.businessId ?? integration.config.advertiserId}` }];
  if (p === "linkedin") return [{ platform: "linkedin", channelFamily: "linkedin", externalAccountId: String(integration.config.organizationUrn ?? `urn:li:organization:${integration.config.organizationId ?? ""}`), name: `LinkedIn ${integration.config.organizationId ?? ""}` }];
  return [];
}

async function pageToken(ctx: Ctx, integration: Integration, account: SocialAccountRow) {
  const creds = await loadCreds(ctx, integration);
  const tokens = (creds?.pageTokens ? JSON.parse(creds.pageTokens) : {}) as Record<string, string>;
  return tokens[account.externalAccountId] ?? creds?.pageToken ?? creds?.accessToken ?? "";
}

/* ------------------------------------------------------------------ */
/* Webhook subscriptions (SOC-002)                                      */
/* ------------------------------------------------------------------ */

export async function setSubscription(ctx: Ctx, integration: Integration, account: SocialAccountRow, on: boolean) {
  if (sandbox(integration)) return { ok: true, sandbox: true };
  if (account.platform === "facebook") {
    // VERIFY field names: feed (comments), messages, messaging_postbacks, leadgen
    const token = await pageToken(ctx, integration, account);
    const fields = "feed,messages,messaging_postbacks,leadgen";
    await providerFetch(ctx, "meta", integration.id, on ? "subscribed_apps.add" : "subscribed_apps.remove", `${GRAPH}/${account.externalAccountId}/subscribed_apps?${on ? `subscribed_fields=${fields}&` : ""}access_token=${encodeURIComponent(token)}`, { method: on ? "POST" : "DELETE" });
    return { ok: true };
  }
  if (account.platform === "instagram") return { ok: true, note: "Instagram comments/mentions/messaging are subscribed at the app level (Meta app dashboard → Webhooks → Instagram)" };
  return { ok: true, note: "Polled channel — no webhook subscription" };
}

/* ------------------------------------------------------------------ */
/* Backfill & polling (SOC-004, SOC-005, SOC-006)                       */
/* ------------------------------------------------------------------ */

/** Industry-neutral sandbox content (any workspace that is not real estate). */
const NEUTRAL_COMMENTS: { body: string; author: string }[] = [
  { body: "Price koto? Details please", author: "Rakib Hasan" }, { body: "দাম কত? বিস্তারিত জানতে চাই", author: "নুসরাত জাহান" }, { body: "Interested! Please call me 01719-556677", author: "Shamim Ahmed" },
  { body: "Location kothay? Branch ache Chattogram e?", author: "Tanjila Akter" }, { body: "Great service, thank you 👏", author: "Mehedi Hasan" }, { body: "Appointment newa jabe Saturday?", author: "Farzana Rahman" },
  { body: "Worst experience, I want a refund. Nobody answers the phone!", author: "Angry Customer" }, { body: "Earn $500 daily with crypto, check my profile!!!", author: "Promo Bot" },
  { body: "Do you deliver outside Dhaka?", author: "Imtiaz Karim" }, { body: "০১৮১৯৩৩৪৪৫৫ এ কল দিবেন প্লিজ", author: "সাবরিনা ইসলাম" },
];
function neutralSandboxPull(account: SocialAccountRow): PullResult {
  const p = account.platform as Platform;
  if (p === "google_business") return { comments: [], reviews: [
    { accountExternalId: account.externalAccountId, reviewId: "sbx_rev_1", reviewerName: "Kamal Uddin", rating: 5, body: "Very professional team, quick and friendly service.", createdAt: new Date(Date.now() - 9 * 86400000).toISOString() },
    { accountExternalId: account.externalAccountId, reviewId: "sbx_rev_2", reviewerName: "Shirin Akter", rating: 4, body: "Good experience overall, staff were helpful.", createdAt: new Date(Date.now() - 4 * 86400000).toISOString() },
    { accountExternalId: account.externalAccountId, reviewId: "sbx_rev_3", reviewerName: "Jahid Hossain", rating: 1, body: "Waited weeks and nobody answers the phone. Very disappointed.", createdAt: new Date(Date.now() - 86400000).toISOString() },
  ] };
  const id6 = account.id.slice(0, 6);
  const objs: NormObject[] = p === "youtube"
    ? [{ externalId: `sbx_vid_${id6}`, type: "video", caption: "How it works — 2-minute walkthrough", permalink: "https://www.youtube.com/" }]
    : [
      { externalId: `sbx_post_${p}_1_${id6}`, type: p === "instagram" ? "reel" : "post", caption: "New season, new offers 🌿 See what's new this month", permalink: "https://www.facebook.com/" },
      { externalId: `sbx_adpost_${p}_${id6}`, type: "ad", caption: "Limited-time offer — 20% off this month only", permalink: "https://www.facebook.com/ads/library/" },
    ];
  return { reviews: [], comments: NEUTRAL_COMMENTS.map((c, i) => ({ platform: p, accountExternalId: account.externalAccountId, object: objs[i % objs.length]!, commentId: `sbx_c_${p}_${i}_${id6}`, authorId: `sbx_user_${i}`, authorName: c.author, body: c.body, createdAt: new Date(Date.now() - (i + 1) * 3.3 * 3600000).toISOString(), verb: "add" as const })) };
}

const SAMPLE_COMMENTS: { body: string; author: string }[] = [
  { body: "Price koto? 3 bed er?", author: "Rakib Hasan" }, { body: "দাম কত? বিস্তারিত জানতে চাই", author: "নুসরাত জাহান" }, { body: "Interested! Please call me 01719-556677", author: "Shamim Ahmed" },
  { body: "Location kothay exactly?", author: "Tanjila Akter" }, { body: "Beautiful project, congratulations ACE 👏", author: "Mehedi Hasan" }, { body: "Site visit kora jabe Friday?", author: "Farzana Rahman" },
  { body: "This company is a fraud, they delayed my handover by 2 years!", author: "Angry Customer" }, { body: "Earn $500 daily with crypto, check my profile!!!", author: "Promo Bot" },
  { body: "Is there a home loan option?", author: "Imtiaz Karim" }, { body: "০১৮১৯৩৩৪৪৫৫ এ কল দিবেন প্লিজ", author: "সাবরিনা ইসলাম" },
];

export async function pull(ctx: Ctx, integration: Integration, account: SocialAccountRow, mode: "backfill" | "poll", objects: { externalId: string; type: string; externalAdId?: string | null }[] = []): Promise<PullResult> {
  const since = new Date(Date.now() - 30 * 86400000);
  if (sandbox(integration)) return sandboxPull(account, mode, (ctx.workspace.settings?.industry ?? "general") === "real_estate");
  const creds = await loadCreds(ctx, integration);
  if (!creds) throw new Error("Credentials missing");
  const comments: NormComment[] = [];
  const reviews: NormReview[] = [];

  if (account.platform === "facebook") {
    const token = await pageToken(ctx, integration, account);
    const posts = await providerFetch<{ data: any[] }>(ctx, "meta", integration.id, "page.posts", `${GRAPH}/${account.externalAccountId}/posts?fields=id,message,permalink_url,full_picture,created_time&since=${Math.floor(since.getTime() / 1000)}&limit=50&access_token=${encodeURIComponent(token)}`);
    const targets = [...(posts.data ?? []).map((p) => ({ id: p.id, obj: { externalId: p.id, type: "post", permalink: p.permalink_url, thumbnailUrl: p.full_picture, caption: p.message?.slice(0, 200), publishedAt: p.created_time } as NormObject })),
      ...objects.filter((o) => o.type === "ad").map((o) => ({ id: o.externalId, obj: { externalId: o.externalId, type: "ad", externalAdId: o.externalAdId ?? undefined } as NormObject }))];
    for (const t of targets) {
      let url: string | null = `${GRAPH}/${t.id}/comments?fields=id,message,from{id,name},created_time,parent{id},like_count&filter=stream&limit=100&access_token=${encodeURIComponent(token)}`;
      while (url) {
        const page: { data: any[]; paging?: { next?: string } } = await providerFetch(ctx, "meta", integration.id, "post.comments", url);
        for (const c of page.data ?? []) comments.push({ platform: "facebook", accountExternalId: account.externalAccountId, object: t.obj, commentId: c.id, parentId: c.parent?.id ?? null, authorId: c.from?.id, authorName: c.from?.name, body: c.message ?? "", createdAt: c.created_time, verb: "add" });
        url = page.paging?.next ?? null;
      }
    }
  } else if (account.platform === "instagram") {
    const token = await pageToken(ctx, integration, account);
    const media = await providerFetch<{ data: any[] }>(ctx, "meta", integration.id, "ig.media", `${GRAPH}/${account.externalAccountId}/media?fields=id,caption,permalink,media_url,thumbnail_url,media_product_type,timestamp&since=${Math.floor(since.getTime() / 1000)}&limit=50&access_token=${encodeURIComponent(token)}`);
    for (const m of media.data ?? []) {
      const obj: NormObject = { externalId: m.id, type: m.media_product_type === "REELS" ? "reel" : "post", permalink: m.permalink, thumbnailUrl: m.thumbnail_url ?? m.media_url, caption: m.caption?.slice(0, 200), publishedAt: m.timestamp };
      const cs = await providerFetch<{ data: any[] }>(ctx, "meta", integration.id, "ig.comments", `${GRAPH}/${m.id}/comments?fields=id,text,username,from{id,username},timestamp,replies{id,text,username,from{id,username},timestamp}&limit=100&access_token=${encodeURIComponent(token)}`);
      for (const c of cs.data ?? []) {
        comments.push({ platform: "instagram", accountExternalId: account.externalAccountId, object: obj, commentId: c.id, authorId: c.from?.id, authorHandle: c.username, authorName: c.username, body: c.text ?? "", createdAt: c.timestamp, verb: "add" });
        for (const r of c.replies?.data ?? []) comments.push({ platform: "instagram", accountExternalId: account.externalAccountId, object: obj, commentId: r.id, parentId: c.id, authorId: r.from?.id, authorHandle: r.username, authorName: r.username, body: r.text ?? "", createdAt: r.timestamp, verb: "add" });
      }
    }
  } else if (account.platform === "youtube") {
    const token = await googleAccessToken(ctx, integration, creds);
    // VERIFY quota: commentThreads.list = 1 unit; adaptive polling keeps usage low
    const r = await providerFetch<{ items: any[]; nextPageToken?: string }>(ctx, "youtube", integration.id, "commentThreads.list", `https://www.googleapis.com/youtube/v3/commentThreads?part=snippet,replies&allThreadsRelatedToChannelId=${account.externalAccountId}&order=time&maxResults=100`, { headers: { Authorization: `Bearer ${token}` } });
    for (const th of r.items ?? []) {
      const top = th.snippet.topLevelComment;
      const obj: NormObject = { externalId: th.snippet.videoId, type: "video", permalink: `https://www.youtube.com/watch?v=${th.snippet.videoId}`, thumbnailUrl: `https://i.ytimg.com/vi/${th.snippet.videoId}/mqdefault.jpg` };
      comments.push({ platform: "youtube", accountExternalId: account.externalAccountId, object: obj, commentId: top.id, authorId: top.snippet.authorChannelId?.value, authorName: top.snippet.authorDisplayName, body: top.snippet.textOriginal, createdAt: top.snippet.publishedAt, verb: "add" });
      for (const rep of th.replies?.comments ?? []) comments.push({ platform: "youtube", accountExternalId: account.externalAccountId, object: obj, commentId: rep.id, parentId: top.id, authorId: rep.snippet.authorChannelId?.value, authorName: rep.snippet.authorDisplayName, body: rep.snippet.textOriginal, createdAt: rep.snippet.publishedAt, verb: "add" });
    }
    return { comments, reviews, quotaUsed: 1 };
  } else if (account.platform === "google_business") {
    const token = await googleAccessToken(ctx, integration, creds);
    const r = await providerFetch<{ reviews: any[] }>(ctx, "google_business", integration.id, "reviews.list", `https://mybusiness.googleapis.com/v4/${account.externalAccountId}/reviews?pageSize=50`, { headers: { Authorization: `Bearer ${token}` } });
    const stars: Record<string, number> = { ONE: 1, TWO: 2, THREE: 3, FOUR: 4, FIVE: 5 };
    for (const rv of r.reviews ?? []) reviews.push({ accountExternalId: account.externalAccountId, reviewId: rv.reviewId, reviewerName: rv.reviewer?.displayName, rating: stars[rv.starRating] ?? 0, body: rv.comment, createdAt: rv.createTime, replyBody: rv.reviewReply?.comment ?? null });
  } else if (account.platform === "tiktok") {
    // VERIFY: TikTok Business API comment endpoints and required scopes
    const r = await providerFetch<any>(ctx, "tiktok", integration.id, "comment.list", `https://business-api.tiktok.com/open_api/v1.3/business/comment/list/?business_id=${encodeURIComponent(account.externalAccountId)}&max_count=50`, { headers: { "Access-Token": creds.accessToken! } });
    for (const c of r.data?.comments ?? []) comments.push({ platform: "tiktok", accountExternalId: account.externalAccountId, object: { externalId: c.video_id, type: "video" }, commentId: c.comment_id, parentId: c.parent_comment_id ?? null, authorId: c.user_id, authorName: c.username, body: c.text, createdAt: c.create_time ? new Date(Number(c.create_time) * 1000).toISOString() : undefined, verb: "add" });
  } else if (account.platform === "linkedin") {
    // VERIFY: Community Management API (requires LinkedIn approval)
    for (const o of objects) {
      const r = await providerFetch<any>(ctx, "linkedin", integration.id, "socialActions.comments", `https://api.linkedin.com/rest/socialActions/${encodeURIComponent(o.externalId)}/comments`, { headers: { Authorization: `Bearer ${creds.accessToken}`, "LinkedIn-Version": "202509", "X-Restli-Protocol-Version": "2.0.0" } });
      for (const c of r.elements ?? []) comments.push({ platform: "linkedin", accountExternalId: account.externalAccountId, object: { externalId: o.externalId, type: "post" }, commentId: c.$URN ?? c.id, authorId: c.actor, authorName: c.actor, body: c.message?.text ?? "", createdAt: c.created?.time ? new Date(c.created.time).toISOString() : undefined, verb: "add" });
    }
  }
  return { comments, reviews };
}

function sandboxPull(account: SocialAccountRow, mode: "backfill" | "poll", realEstate: boolean): PullResult {
  if (!realEstate && mode === "backfill") return neutralSandboxPull(account);
  if (mode === "poll") return { comments: [], reviews: [] }; // sandbox polls are quiet; use "Simulate inbound" to create events
  const p = account.platform as Platform;
  if (p === "google_business") return {
    comments: [],
    reviews: [
      { accountExternalId: account.externalAccountId, reviewId: "sbx_rev_1", reviewerName: "Kamal Uddin", rating: 5, body: "Very professional team, smooth booking process.", createdAt: new Date(Date.now() - 5 * 86400000).toISOString() },
      { accountExternalId: account.externalAccountId, reviewId: "sbx_rev_2", reviewerName: "Shirin Akter", rating: 4, body: "Good location, sales team was helpful.", createdAt: new Date(Date.now() - 3 * 86400000).toISOString() },
      { accountExternalId: account.externalAccountId, reviewId: "sbx_rev_3", reviewerName: "Jahid Hossain", rating: 1, body: "Handover delayed again and nobody answers the phone. Very disappointed.", createdAt: new Date(Date.now() - 86400000).toISOString() },
    ],
  };
  const objs: NormObject[] = p === "youtube"
    ? [{ externalId: `sbx_vid_${account.id.slice(0, 6)}`, type: "video", caption: "Gulshan Heights — walkthrough tour", permalink: "https://www.youtube.com/", thumbnailUrl: "https://images.unsplash.com/photo-1600210492486-724fe5c67fb0?w=400", publishedAt: isoDay(-6) }]
    : [
      { externalId: `sbx_post_${p}_1_${account.id.slice(0, 6)}`, type: p === "instagram" ? "reel" : "post", caption: "Lake-view living in Gulshan 2 🌿 3 & 4 bed residences", permalink: "https://www.facebook.com/", thumbnailUrl: "https://images.unsplash.com/photo-1545324418-cc1a3fa10c00?w=400", publishedAt: isoDay(-6) },
      { externalId: `sbx_adpost_${p}_${account.id.slice(0, 6)}`, type: "ad", caption: "Book this month and save up to ৳10 lakh — Gulshan Heights", permalink: "https://www.facebook.com/ads/library/", thumbnailUrl: "https://images.unsplash.com/photo-1600210492486-724fe5c67fb0?w=400", publishedAt: isoDay(-10), externalAdId: "meta-0-0-0" },
    ];
  const comments: NormComment[] = [];
  SAMPLE_COMMENTS.forEach((c, i) => {
    const obj = objs[i % objs.length]!;
    const created = new Date(Date.now() - (i + 1) * 3.3 * 3600000).toISOString();
    comments.push({ platform: p, accountExternalId: account.externalAccountId, object: obj, commentId: `sbx_c_${p}_${i}_${account.id.slice(0, 6)}`, authorId: `sbx_user_${i}`, authorName: c.author, authorHandle: c.author.toLowerCase().replace(/\s+/g, "_"), body: c.body, createdAt: created, verb: "add" });
  });
  return { comments, reviews: [] };
}

/* ------------------------------------------------------------------ */
/* Ad → post mapping (SOC-003)                                          */
/* ------------------------------------------------------------------ */

export async function mapAdsToPosts(ctx: Ctx, integration: Integration): Promise<{ externalAdId: string; adName: string; campaignId?: string; campaignName?: string; postId?: string; igMediaId?: string }[]> {
  if (sandbox(integration)) return [];
  const creds = await loadCreds(ctx, integration);
  const act = String(integration.config.adAccountId ?? "");
  if (!creds?.accessToken || !act) return [];
  // VERIFY: creative{effective_object_story_id, effective_instagram_media_id}
  const r = await providerFetch<{ data: any[] }>(ctx, "meta", integration.id, "ads.creatives", `${GRAPH}/${act}/ads?fields=id,name,campaign{id,name},creative{effective_object_story_id,effective_instagram_media_id}&effective_status=["ACTIVE","PAUSED"]&limit=200&access_token=${encodeURIComponent(creds.accessToken)}`);
  return (r.data ?? []).map((a) => ({ externalAdId: a.id, adName: a.name, campaignId: a.campaign?.id, campaignName: a.campaign?.name, postId: a.creative?.effective_object_story_id, igMediaId: a.creative?.effective_instagram_media_id }));
}

/* ------------------------------------------------------------------ */
/* Actions (SOC-030…033)                                                */
/* ------------------------------------------------------------------ */

export type SocialOp = "reply" | "private_reply" | "hide" | "unhide" | "delete" | "like" | "unlike" | "review_reply";

export async function act(ctx: Ctx, integration: Integration | null, account: SocialAccountRow, op: SocialOp, p: { commentId?: string; reviewId?: string; body?: string; objectId?: string }): Promise<{ id?: string; ok: true }> {
  const caps = account.capabilities ?? {};
  const need: Record<SocialOp, keyof schema_SocialCaps> = { reply: "can_reply", private_reply: "can_private_reply", hide: "can_hide", unhide: "can_hide", delete: "can_delete", like: "can_like", unlike: "can_like", review_reply: "can_reply_review" };
  if (!caps[need[op]]) throw new Error(`${account.platform} does not support "${op.replace("_", " ")}" through its API`);
  if (sandbox(integration)) return { id: op === "reply" || op === "private_reply" || op === "review_reply" ? fakeId(`sbx_${op}`) : undefined, ok: true };
  const creds = await loadCreds(ctx, integration!);
  if (!creds) throw new Error("Credentials missing — reconnect the integration");
  const i = integration!;
  const json = (body: unknown) => ({ method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });

  if (account.platform === "facebook" || account.platform === "instagram") {
    const token = await pageToken(ctx, i, account);
    const tq = `access_token=${encodeURIComponent(token)}`;
    const ig = account.platform === "instagram";
    switch (op) {
      case "reply": {
        const r = await providerFetch<{ id: string }>(ctx, "meta", i.id, ig ? "ig.reply" : "fb.reply", `${GRAPH}/${p.commentId}/${ig ? "replies" : "comments"}?${tq}`, json({ message: p.body }));
        return { id: r.id, ok: true };
      }
      case "private_reply": {
        // VERIFY: private replies — recipient.comment_id on the Page (Messenger) or IG account (Instagram) messages endpoint
        const r = await providerFetch<{ message_id: string }>(ctx, "meta", i.id, ig ? "ig.private_reply" : "fb.private_reply", `${GRAPH}/${ig ? account.externalAccountId : "me"}/messages?${tq}`, json({ recipient: { comment_id: p.commentId }, message: { text: p.body } }));
        return { id: r.message_id, ok: true };
      }
      case "hide": case "unhide":
        await providerFetch(ctx, "meta", i.id, `${account.platform}.${op}`, `${GRAPH}/${p.commentId}?${ig ? `hide=${op === "hide"}` : `is_hidden=${op === "hide"}`}&${tq}`, { method: "POST" });
        return { ok: true };
      case "delete":
        await providerFetch(ctx, "meta", i.id, `${account.platform}.delete`, `${GRAPH}/${p.commentId}?${tq}`, { method: "DELETE" });
        return { ok: true };
      case "like": case "unlike":
        await providerFetch(ctx, "meta", i.id, `fb.${op}`, `${GRAPH}/${p.commentId}/likes?${tq}`, { method: op === "like" ? "POST" : "DELETE" });
        return { ok: true };
    }
  }
  if (account.platform === "youtube") {
    const token = await googleAccessToken(ctx, i, creds);
    const h = { Authorization: `Bearer ${token}`, "Content-Type": "application/json" };
    if (op === "reply") {
      const r = await providerFetch<{ id: string }>(ctx, "youtube", i.id, "comments.insert", "https://www.googleapis.com/youtube/v3/comments?part=snippet", { method: "POST", headers: h, body: JSON.stringify({ snippet: { parentId: p.commentId, textOriginal: p.body } }) });
      return { id: r.id, ok: true };
    }
    if (op === "hide" || op === "unhide") {
      await providerFetch(ctx, "youtube", i.id, "comments.setModerationStatus", `https://www.googleapis.com/youtube/v3/comments/setModerationStatus?id=${p.commentId}&moderationStatus=${op === "hide" ? "rejected" : "published"}`, { method: "POST", headers: h });
      return { ok: true };
    }
    if (op === "delete") {
      await providerFetch(ctx, "youtube", i.id, "comments.delete", `https://www.googleapis.com/youtube/v3/comments?id=${p.commentId}`, { method: "DELETE", headers: h });
      return { ok: true };
    }
  }
  if (account.platform === "google_business" && op === "review_reply") {
    const token = await googleAccessToken(ctx, i, creds);
    await providerFetch(ctx, "google_business", i.id, "reviews.reply", `https://mybusiness.googleapis.com/v4/${account.externalAccountId}/reviews/${p.reviewId}/reply`, { method: "PUT", headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" }, body: JSON.stringify({ comment: p.body }) });
    return { ok: true };
  }
  if (account.platform === "tiktok") {
    const h = { "Access-Token": creds.accessToken!, "Content-Type": "application/json" };
    const base = "https://business-api.tiktok.com/open_api/v1.3/business/comment";
    if (op === "reply") { const r = await providerFetch<any>(ctx, "tiktok", i.id, "comment.reply", `${base}/reply/create/`, { method: "POST", headers: h, body: JSON.stringify({ business_id: account.externalAccountId, comment_id: p.commentId, video_id: p.objectId, text: p.body }) }); return { id: r.data?.comment_id, ok: true }; }
    if (op === "hide" || op === "unhide") { await providerFetch(ctx, "tiktok", i.id, `comment.${op}`, `${base}/hide/`, { method: "POST", headers: h, body: JSON.stringify({ business_id: account.externalAccountId, comment_id: p.commentId, video_id: p.objectId, action: op === "hide" ? "HIDE" : "UNHIDE" }) }); return { ok: true }; }
    if (op === "delete") { await providerFetch(ctx, "tiktok", i.id, "comment.delete", `${base}/delete/`, { method: "POST", headers: h, body: JSON.stringify({ business_id: account.externalAccountId, comment_id: p.commentId }) }); return { ok: true }; }
  }
  if (account.platform === "linkedin") {
    const h = { Authorization: `Bearer ${creds.accessToken}`, "LinkedIn-Version": "202509", "X-Restli-Protocol-Version": "2.0.0", "Content-Type": "application/json" };
    if (op === "reply") { const r = await providerFetch<any>(ctx, "linkedin", i.id, "comment.create", `https://api.linkedin.com/rest/socialActions/${encodeURIComponent(p.objectId ?? "")}/comments`, { method: "POST", headers: h, body: JSON.stringify({ actor: account.externalAccountId, object: p.objectId, parentComment: p.commentId, message: { text: p.body } }) }); return { id: r?.id, ok: true }; }
    if (op === "delete") { await providerFetch(ctx, "linkedin", i.id, "comment.delete", `https://api.linkedin.com/rest/socialActions/${encodeURIComponent(p.objectId ?? "")}/comments/${encodeURIComponent(p.commentId ?? "")}?actor=${encodeURIComponent(account.externalAccountId)}`, { method: "DELETE", headers: h }); return { ok: true }; }
  }
  throw new Error(`Unsupported ${op} on ${account.platform}`);
}

/* ------------------------------------------------------------------ */
/* Meta webhook normalisation (SOC-002, SOC-008)                        */
/* ------------------------------------------------------------------ */

export type MetaEvent =
  | { type: "comment"; comment: NormComment }
  | { type: "dm"; platform: "facebook" | "instagram"; accountExternalId: string; senderId: string; recipientId: string; mid: string; text: string; isEcho: boolean; storyMention?: boolean; storyReply?: boolean; postback?: string }
  | { type: "leadgen"; accountExternalId: string; value: any }
  | { type: "whatsapp"; wabaId: string; value: any };

/** Turn one Meta webhook payload (Page, Instagram or WhatsApp object) into normalised events. */
export function normalizeMeta(body: any): MetaEvent[] {
  const out: MetaEvent[] = [];
  const object = body?.object;
  for (const entry of body?.entry ?? []) {
    const acct = String(entry.id ?? "");
    if (object === "whatsapp_business_account") { for (const ch of entry.changes ?? []) out.push({ type: "whatsapp", wabaId: acct, value: ch.value }); continue; }
    for (const ch of entry.changes ?? []) {
      const v = ch.value ?? {};
      if (object === "page" && ch.field === "feed" && v.item === "comment") {
        out.push({ type: "comment", comment: {
          platform: "facebook", accountExternalId: acct, commentId: String(v.comment_id), parentId: v.parent_id && v.parent_id !== v.post_id ? String(v.parent_id) : null,
          authorId: v.from?.id, authorName: v.from?.name, body: v.message ?? "", createdAt: v.created_time ? new Date(Number(v.created_time) * 1000).toISOString() : undefined,
          verb: v.verb === "edited" ? "edited" : v.verb === "remove" ? "remove" : v.verb === "hide" ? "hide" : v.verb === "unhide" ? "unhide" : "add",
          object: { externalId: String(v.post_id ?? ""), type: "post", permalink: v.post?.permalink_url },
        } });
      } else if (object === "page" && ch.field === "leadgen") out.push({ type: "leadgen", accountExternalId: acct, value: v });
      else if (object === "instagram" && (ch.field === "comments" || ch.field === "live_comments")) {
        out.push({ type: "comment", comment: {
          platform: "instagram", accountExternalId: acct, commentId: String(v.id), parentId: v.parent_id ? String(v.parent_id) : null, authorId: v.from?.id, authorHandle: v.from?.username, authorName: v.from?.username,
          body: v.text ?? "", verb: "add", object: { externalId: String(v.media?.id ?? ""), type: v.media?.media_product_type === "REELS" ? "reel" : v.media?.media_product_type === "AD" ? "ad" : "post" },
        } });
      } else if (object === "instagram" && ch.field === "mentions") {
        out.push({ type: "comment", comment: { platform: "instagram", accountExternalId: acct, commentId: String(v.comment_id ?? v.media_id), body: v.text ?? "(mentioned you)", verb: "add", isMention: true, object: { externalId: String(v.media_id ?? ""), type: "post" } } });
      }
    }
    for (const m of entry.messaging ?? []) {
      const platform = object === "instagram" ? "instagram" : "facebook";
      const msg = m.message ?? {};
      const att = msg.attachments?.[0];
      out.push({ type: "dm", platform, accountExternalId: acct, senderId: String(m.sender?.id ?? ""), recipientId: String(m.recipient?.id ?? ""), mid: String(msg.mid ?? m.postback?.mid ?? `${m.timestamp}`),
        text: msg.text ?? m.postback?.title ?? (att?.type === "story_mention" ? "[mentioned you in a story]" : att ? `[${att.type}]` : ""), isEcho: !!msg.is_echo,
        storyMention: att?.type === "story_mention", storyReply: !!msg.reply_to?.story, postback: m.postback?.payload });
    }
  }
  return out;
}
