/**
 * Module 11 — social account lifecycle (SOC-001…007): discovery, activation + webhook subscription, backfill,
 * polling, token health, ad→post mapping, inbound Meta event fan-out and the sandbox simulator.
 */
import { and, eq, inArray } from "drizzle-orm";
import { getDb, schema } from "@/db";
import type { Ctx } from "@/lib/auth";
import { systemCtx } from "@/lib/auth";
import { ApiError } from "@/lib/api";
import { audit } from "@/lib/audit";
import { emit } from "@/lib/webhooks";
import { enqueue } from "@/lib/jobs";
import { CAPABILITIES, discoverAccounts, mapAdsToPosts, pull, setSubscription, type MetaEvent, type NormComment, type Platform } from "@/connectors/social";
import { getAccount, ingestComment, ingestReview } from "./social";

export const SOCIAL_PROVIDERS = ["meta", "youtube", "google_business", "tiktok", "linkedin"];
export const POLLED_PLATFORMS = ["youtube", "google_business", "tiktok", "linkedin"];
type Account = typeof schema.socialAccounts.$inferSelect;

async function integrationOf(ctx: Pick<Ctx, "db">, a: Account) {
  if (!a.integrationId) throw new ApiError(409, "not_connected", "This social account has no integration");
  const i = await ctx.db.query.integrations.findFirst({ where: eq(schema.integrations.id, a.integrationId) });
  if (!i) throw new ApiError(409, "not_connected", "Integration removed — reconnect it in Integrations");
  return i;
}

/** SOC-001: list every page / IG account / channel / location the connected token can manage. New ones start inactive. */
export async function discover(ctx: Ctx, integrationId?: string) {
  const ints = await ctx.db.select().from(schema.integrations).where(and(eq(schema.integrations.workspaceId, ctx.workspace.id), inArray(schema.integrations.provider, SOCIAL_PROVIDERS), integrationId ? eq(schema.integrations.id, integrationId) : undefined));
  const found: Account[] = [];
  for (const i of ints) {
    if (i.status !== "connected") continue;
    const list = await discoverAccounts(ctx, i);
    const pageTokens: Record<string, string> = {};
    for (const d of list) {
      if (d.pageToken) pageTokens[d.externalAccountId] = d.pageToken;
      const [row] = await ctx.db.insert(schema.socialAccounts).values({ workspaceId: ctx.workspace.id, integrationId: i.id, channelFamily: d.channelFamily, platform: d.platform, externalAccountId: d.externalAccountId, name: d.name, avatarUrl: d.avatarUrl ?? null, capabilities: CAPABILITIES[d.platform] })
        .onConflictDoUpdate({ target: [schema.socialAccounts.workspaceId, schema.socialAccounts.platform, schema.socialAccounts.externalAccountId], set: { name: d.name, avatarUrl: d.avatarUrl ?? null, integrationId: i.id, capabilities: CAPABILITIES[d.platform], updatedAt: new Date() } }).returning();
      found.push(row!);
    }
    if (Object.keys(pageTokens).length && i.tokenRef) {
      const { readSecret, writeSecret } = await import("@/lib/vault");
      const creds = (await readSecret(ctx.db, i.tokenRef)) ?? {};
      await writeSecret(ctx.db, ctx.workspace.id, { ...creds, pageTokens: JSON.stringify(pageTokens) }, i.tokenRef);
    }
  }
  return found;
}

export async function setActive(ctx: Ctx, accountId: string, active: boolean) {
  const a = await getAccount(ctx, accountId);
  const i = await integrationOf(ctx, a);
  let subscribed = a.webhookSubscribed;
  let note: string | undefined;
  try {
    const r = await setSubscription(ctx, i, a, active);
    subscribed = active && a.platform === "facebook" ? true : active ? a.platform === "instagram" : false;
    note = (r as { note?: string }).note;
  } catch (e) {
    await ctx.db.update(schema.socialAccounts).set({ lastError: (e as Error).message.slice(0, 500) }).where(eq(schema.socialAccounts.id, a.id));
    throw new ApiError(502, "provider_error", `Could not ${active ? "subscribe" : "unsubscribe"}: ${(e as Error).message}`);
  }
  const [u] = await ctx.db.update(schema.socialAccounts).set({ status: active ? "active" : "inactive", webhookSubscribed: subscribed, lastError: null, updatedAt: new Date(), ...(active && !a.backfill.status ? { backfill: { status: "queued" } } : {}) }).where(eq(schema.socialAccounts.id, a.id)).returning();
  await audit(ctx, active ? "social.account_activate" : "social.account_deactivate", "social_account", a.id, { status: a.status }, { status: u!.status });
  if (active && !a.backfill.status) await enqueue(ctx.db, "social.backfill", { workspaceId: ctx.workspace.id, accountId: a.id }, { workspaceId: ctx.workspace.id, idempotencyKey: `bf:${a.id}` });
  return { account: u!, note };
}

/** SOC-004: last 30 days of comments/reviews; never triggers auto-replies on historical items. */
export async function runBackfill(ctx: Ctx, accountId: string) {
  const a = await getAccount(ctx, accountId);
  const i = await integrationOf(ctx, a);
  await ctx.db.update(schema.socialAccounts).set({ backfill: { status: "running", done: 0 } }).where(eq(schema.socialAccounts.id, a.id));
  try {
    const ads = await ctx.db.select({ externalId: schema.socialObjects.externalId, type: schema.socialObjects.type, externalAdId: schema.socialObjects.externalAdId }).from(schema.socialObjects).where(and(eq(schema.socialObjects.socialAccountId, a.id), eq(schema.socialObjects.type, "ad")));
    const r = await pull(ctx, i, a, "backfill", ads);
    let done = 0;
    for (const c of r.comments) { await ingestComment(ctx, a, c, { source: "backfill" }); done++; }
    for (const rv of r.reviews) { await ingestReview(ctx, a, rv, { source: "backfill" }); done++; }
    const [u] = await ctx.db.update(schema.socialAccounts).set({ backfill: { status: "done", done, total: done, finishedAt: new Date().toISOString() }, pollCursor: r.cursor ?? a.pollCursor, lastPolledAt: new Date() }).where(eq(schema.socialAccounts.id, a.id)).returning();
    return u!;
  } catch (e) {
    await ctx.db.update(schema.socialAccounts).set({ backfill: { status: "failed", error: (e as Error).message.slice(0, 300) }, lastError: (e as Error).message.slice(0, 500) }).where(eq(schema.socialAccounts.id, a.id));
    throw e;
  }
}

/** SOC-005/006: polling for channels without webhooks (and as a webhook safety net). */
export async function pollAccount(ctx: Ctx, accountId: string) {
  const a = await getAccount(ctx, accountId);
  if (a.status !== "active") return { created: 0 };
  const i = await integrationOf(ctx, a);
  const r = await pull(ctx, i, a, "poll");
  let created = 0;
  for (const c of r.comments) if ((await ingestComment(ctx, a, c, { source: "poll" })).status === "created") created++;
  for (const rv of r.reviews) if ((await ingestReview(ctx, a, rv, { source: "poll" })).status === "created") created++;
  await ctx.db.update(schema.socialAccounts).set({ lastPolledAt: new Date(), pollCursor: r.cursor ?? a.pollCursor, lastError: null }).where(eq(schema.socialAccounts.id, a.id));
  return { created, quotaUsed: r.quotaUsed ?? 0 };
}

/** Sandbox / QA helper: inject an inbound comment, review or DM as if the platform had sent it. */
export async function simulateInbound(ctx: Ctx, accountId: string, input: { kind: "comment" | "review" | "dm"; text: string; authorName?: string; authorId?: string; rating?: number; objectExternalId?: string; objectCaption?: string; externalAdId?: string; parentCommentId?: string }) {
  const a = await getAccount(ctx, accountId);
  const i = a.integrationId ? await ctx.db.query.integrations.findFirst({ where: eq(schema.integrations.id, a.integrationId) }) : null;
  if (i?.mode === "live" && process.env.NODE_ENV === "production" && process.env.ALLOW_SOCIAL_SIMULATE !== "true") throw new ApiError(403, "forbidden", "Simulation is only available for sandbox accounts");
  const author = input.authorId ?? `sim_${(input.authorName ?? "user").toLowerCase().replace(/[^a-z0-9]+/g, "_")}`;
  if (input.kind === "review") {
    if (a.platform !== "google_business") throw new ApiError(422, "validation_failed", "Reviews only exist on Google Business Profile accounts");
    return ingestReview(ctx, a, { accountExternalId: a.externalAccountId, reviewId: `sim_rev_${Date.now()}`, reviewerName: input.authorName ?? "Reviewer", rating: Math.min(5, Math.max(1, input.rating ?? 5)), body: input.text, createdAt: new Date().toISOString() }, { source: "simulate" });
  }
  if (input.kind === "dm") {
    if (!["facebook", "instagram"].includes(a.platform)) throw new ApiError(422, "validation_failed", "DMs can be simulated on Facebook or Instagram accounts");
    const { receiveMessage } = await import("./messaging");
    return receiveMessage(ctx, { channel: a.platform === "facebook" ? "messenger" : "instagram", from: author, psid: author, name: input.authorName, body: input.text, providerMessageId: `sim_mid_${Date.now()}` });
  }
  const c: NormComment = {
    platform: a.platform as Platform, accountExternalId: a.externalAccountId, commentId: `sim_c_${Date.now()}_${Math.random().toString(36).slice(2, 7)}`, parentId: input.parentCommentId ?? null,
    authorId: author, authorName: input.authorName ?? "Social user", body: input.text, createdAt: new Date().toISOString(), verb: "add",
    object: { externalId: input.objectExternalId ?? `sim_post_${a.id.slice(0, 6)}`, type: input.externalAdId ? "ad" : "post", caption: input.objectCaption ?? "Sample post", externalAdId: input.externalAdId },
  };
  return ingestComment(ctx, a, c, { source: "simulate" });
}

/** Meta events (feed comments, IG comments/mentions, Messenger/IG DMs) for one workspace. */
export async function handleMetaEvents(ctx: Ctx, events: MetaEvent[]) {
  let handled = 0;
  for (const ev of events) {
    if (ev.type === "comment") {
      const a = await ctx.db.query.socialAccounts.findFirst({ where: and(eq(schema.socialAccounts.workspaceId, ctx.workspace.id), eq(schema.socialAccounts.platform, ev.comment.platform), eq(schema.socialAccounts.externalAccountId, ev.comment.accountExternalId)) });
      if (!a || a.status !== "active") continue;
      await ingestComment(ctx, a, ev.comment, { source: "webhook" });
      handled++;
    } else if (ev.type === "dm") {
      if (ev.isEcho || !ev.text) continue; // our own outbound echoes
      const a = await ctx.db.query.socialAccounts.findFirst({ where: and(eq(schema.socialAccounts.workspaceId, ctx.workspace.id), eq(schema.socialAccounts.externalAccountId, ev.accountExternalId)) });
      const { receiveMessage } = await import("./messaging");
      const msg = await receiveMessage(ctx, { channel: ev.platform === "facebook" ? "messenger" : "instagram", from: ev.senderId, psid: ev.senderId, body: ev.text, providerMessageId: ev.mid });
      const conv = await ctx.db.query.conversations.findFirst({ where: eq(schema.conversations.id, msg.conversationId) });
      if (conv && a && !conv.socialAccountId) await ctx.db.update(schema.conversations).set({ socialAccountId: a.id, ...(ev.storyMention || ev.storyReply ? { tags: [...new Set([...(conv.tags ?? []), ev.storyMention ? "story_mention" : "story_reply"])] } : {}) }).where(eq(schema.conversations.id, conv.id));
      if (a) await ctx.db.update(schema.socialAccounts).set({ lastEventAt: new Date() }).where(eq(schema.socialAccounts.id, a.id));
      handled++;
    }
  }
  return handled;
}

/** App-level Meta webhook fan-out: which workspaces own this page / IG account? (spec §6) */
export async function workspacesForMetaAccount(externalAccountId: string) {
  const db = await getDb();
  const rows = await db.select({ ws: schema.socialAccounts.workspaceId }).from(schema.socialAccounts).where(and(eq(schema.socialAccounts.externalAccountId, externalAccountId), eq(schema.socialAccounts.status, "active")));
  return [...new Set(rows.map((r) => r.ws))];
}

/* ---------------- periodic ---------------- */

export async function enqueuePolls(ctx: Ctx) {
  const accts = await ctx.db.select().from(schema.socialAccounts).where(and(eq(schema.socialAccounts.workspaceId, ctx.workspace.id), eq(schema.socialAccounts.status, "active")));
  const every = Number(process.env.SOCIAL_POLL_MINUTES ?? 5);
  const slot = Math.floor(Date.now() / (every * 60000));
  for (const a of accts) {
    // polled channels on their schedule; webhook channels get a 30-minute safety net (SOC-005)
    const interval = POLLED_PLATFORMS.includes(a.platform) ? every : 30;
    if (a.lastPolledAt && Date.now() - a.lastPolledAt.getTime() < interval * 60000) continue;
    await enqueue(ctx.db, "social.poll", { workspaceId: ctx.workspace.id, accountId: a.id }, { workspaceId: ctx.workspace.id, idempotencyKey: `poll:${a.id}:${slot}`, maxAttempts: 2 });
  }
}

/** SOC-007: token health — disconnected accounts raise alerts and a webhook. */
export async function tokenHealth(ctx: Ctx) {
  const accts = await ctx.db.select().from(schema.socialAccounts).where(and(eq(schema.socialAccounts.workspaceId, ctx.workspace.id), inArray(schema.socialAccounts.status, ["active", "error"])));
  let flagged = 0;
  for (const a of accts) {
    const i = a.integrationId ? await ctx.db.query.integrations.findFirst({ where: eq(schema.integrations.id, a.integrationId) }) : null;
    const bad = !i || ["expired", "error", "disconnected"].includes(i.status) || (i.expiresAt && i.expiresAt < new Date());
    if (!bad) continue;
    await ctx.db.update(schema.socialAccounts).set({ status: "disconnected", lastError: i?.lastError ?? "Token expired or integration removed" }).where(eq(schema.socialAccounts.id, a.id));
    await emit(ctx.db, ctx.workspace.id, "social_account.disconnected", { social_account_id: a.id, platform: a.platform, name: a.name, reason: i?.lastError ?? "token expired" });
    const { notifyAdmins } = await import("./notify");
    await notifyAdmins(ctx, "integration", `${a.name} disconnected`, "Reconnect it to keep receiving comments and messages", "/settings/social");
    flagged++;
  }
  return flagged;
}

/** SOC-015: map ads to their underlying posts so ad comments show campaign context. */
export async function syncAdMap(ctx: Ctx) {
  const ints = await ctx.db.select().from(schema.integrations).where(and(eq(schema.integrations.workspaceId, ctx.workspace.id), eq(schema.integrations.provider, "meta"), eq(schema.integrations.status, "connected")));
  let mapped = 0;
  for (const i of ints) {
    const list = await mapAdsToPosts(ctx, i);
    for (const m of list) {
      const postId = m.postId ?? m.igMediaId;
      if (!postId) continue;
      const ad = await ctx.db.query.ads.findFirst({ where: and(eq(schema.ads.workspaceId, ctx.workspace.id), eq(schema.ads.externalId, m.externalAdId)) });
      const r = await ctx.db.update(schema.socialObjects).set({ type: "ad", externalAdId: m.externalAdId, adId: ad?.id ?? null, campaignName: m.campaignName ?? null, updatedAt: new Date() }).where(and(eq(schema.socialObjects.workspaceId, ctx.workspace.id), eq(schema.socialObjects.externalId, postId))).returning({ id: schema.socialObjects.id });
      if (!r.length) {
        const acct = await ctx.db.query.socialAccounts.findFirst({ where: and(eq(schema.socialAccounts.workspaceId, ctx.workspace.id), eq(schema.socialAccounts.platform, m.igMediaId && !m.postId ? "instagram" : "facebook"), eq(schema.socialAccounts.status, "active")) });
        if (acct) await ctx.db.insert(schema.socialObjects).values({ workspaceId: ctx.workspace.id, socialAccountId: acct.id, type: "ad", externalId: postId, externalAdId: m.externalAdId, adId: ad?.id ?? null, campaignName: m.campaignName ?? null }).onConflictDoNothing();
      }
      mapped++;
    }
  }
  return mapped;
}

export async function systemSocialCtx(workspaceId: string) {
  return systemCtx(workspaceId, { type: "system", id: null, name: "Social inbox" });
}
