/**
 * Module 11 — Social inbox & engagement (SOC-*).
 * Ingest order (spec §10): dedupe → store → identity → moderation rules → classification → auto-reply/routing rules → notifications.
 * Every outbound platform action goes through connectors/social.ts.
 */
import { and, asc, desc, eq, gte, inArray, isNull, lte, or, sql } from "drizzle-orm";
import { schema } from "@/db";
import type { Ctx } from "@/lib/auth";
import { activeUsers } from "@/lib/auth";
import type { RuleAction, RuleConditions, SocialSettings } from "@/db/schema";
import { audit } from "@/lib/audit";
import { emit } from "@/lib/webhooks";
import { enqueue } from "@/lib/jobs";
import { ApiError } from "@/lib/api";
import { can } from "@/lib/rbac";
import { fullName, localMinutes, renderTemplate } from "@/lib/util";
import { CAPABILITIES, CHANNEL_FOR, IDENTITY_TYPE, PRIVATE_REPLY_DAYS, act, type NormComment, type NormReview, type Platform, type SocialOp } from "@/connectors/social";
import { classify, containsWord, LEAD_INTENTS, type Classification } from "./social-text";
import { notifyUser, notifyAdmins } from "./notify";

type Conversation = typeof schema.conversations.$inferSelect;
type Account = typeof schema.socialAccounts.$inferSelect;
type CommentRow = typeof schema.comments.$inferSelect;
type By = { type: "user" | "rule" | "ai"; userId?: string | null; ruleId?: string; name?: string };

export const SOCIAL_CHANNELS = ["facebook_comment", "instagram_comment", "tiktok", "linkedin", "youtube", "google_review"];
const DM_WINDOW_HOURS = 24; // WhatsApp / Messenger / Instagram standard window — VERIFY
const settings = (ctx: Pick<Ctx, "workspace">): SocialSettings => ctx.workspace.settings?.social ?? {};

/* ------------------------------------------------------------------ */
/* Helpers                                                              */
/* ------------------------------------------------------------------ */

async function integrationOf(ctx: Pick<Ctx, "db">, account: Account) {
  return account.integrationId ? (await ctx.db.query.integrations.findFirst({ where: eq(schema.integrations.id, account.integrationId) })) ?? null : null;
}

export async function getAccount(ctx: Pick<Ctx, "db" | "workspace">, id: string) {
  const a = await ctx.db.query.socialAccounts.findFirst({ where: and(eq(schema.socialAccounts.id, id), eq(schema.socialAccounts.workspaceId, ctx.workspace.id)) });
  if (!a) throw new ApiError(404, "not_found", "Social account not found");
  return a;
}

/** SOC-091: agents restricted to specific social accounts; empty list = all. */
export async function allowedAccountIds(ctx: Ctx): Promise<string[] | null> {
  if (!ctx.user) return null;
  const m = await ctx.db.query.memberships.findFirst({ where: and(eq(schema.memberships.workspaceId, ctx.workspace.id), eq(schema.memberships.userId, ctx.user.id)) });
  return m?.socialAccountIds?.length ? m.socialAccountIds : null;
}

export function assertSocial(ctx: Ctx, need: "view" | "reply" | "moderate" | "rules" | "ai" | "analytics") {
  const ok = need === "view" ? can(ctx.perms, "social", "view") : need === "reply" ? can(ctx.perms, "social", "edit") : need === "moderate" ? can(ctx.perms, "social_moderate", "edit")
    : need === "rules" ? can(ctx.perms, "social_rules", "edit") : need === "ai" ? can(ctx.perms, "social_ai", "edit") : can(ctx.perms, "social_analytics", "view");
  if (!ok) throw new ApiError(403, "forbidden", `Your role is missing the social.${need === "rules" ? "rules.manage" : need === "ai" ? "ai.autopilot.manage" : need === "analytics" ? "analytics.view" : need} permission`);
}

async function assertConversationAccess(ctx: Ctx, conv: Conversation, need: "view" | "reply" = "view") {
  const social = conv.kind !== "dm";
  if (social) assertSocial(ctx, need);
  else if (!can(ctx.perms, "messaging", need === "view" ? "view" : "edit")) throw new ApiError(403, "forbidden", "No access to messaging");
  const level = social ? ctx.perms.social : ctx.perms.messaging;
  if (level === "C:assigned" && conv.assigneeId !== ctx.user?.id) throw new ApiError(403, "forbidden", "This conversation is assigned to someone else");
  const allowed = await allowedAccountIds(ctx);
  if (allowed && conv.socialAccountId && !allowed.includes(conv.socialAccountId)) throw new ApiError(403, "forbidden", "You don't have access to this social account");
}

/** Business-hours-aware due date (SOC-071). */
export function addBusinessMinutes(from: Date, minutes: number, tz: string, hours?: SocialSettings["hours"]) {
  if (!hours?.days?.length) return new Date(from.getTime() + minutes * 60000);
  const [sh, sm] = hours.start.split(":").map(Number) as [number, number];
  const [eh, em] = hours.end.split(":").map(Number) as [number, number];
  const open = sh * 60 + sm, close = eh * 60 + em;
  let t = new Date(from);
  let left = minutes;
  for (let guard = 0; left > 0 && guard < 60 * 24 * 14; guard++) {
    const day = Number(new Intl.DateTimeFormat("en-US", { timeZone: tz, weekday: "short" }).formatToParts(t).find((p) => p.type === "weekday") ? ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"].indexOf(new Intl.DateTimeFormat("en-US", { timeZone: tz, weekday: "short" }).format(t)) : 0);
    const m = localMinutes(t, tz);
    if (hours.days.includes(day) && m >= open && m < close) {
      const step = Math.min(left, close - m);
      t = new Date(t.getTime() + step * 60000);
      left -= step;
    } else t = new Date(t.getTime() + 15 * 60000 - (t.getTime() % (15 * 60000)));
  }
  return t;
}

export function isBusinessHours(ws: Ctx["workspace"], at = new Date()) {
  const h = ws.settings?.social?.hours;
  if (!h?.days?.length) return true;
  const day = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"].indexOf(new Intl.DateTimeFormat("en-US", { timeZone: ws.timezone, weekday: "short" }).format(at));
  const m = localMinutes(at, ws.timezone);
  const [sh, sm] = h.start.split(":").map(Number) as [number, number];
  const [eh, em] = h.end.split(":").map(Number) as [number, number];
  return h.days.includes(day) && m >= sh * 60 + sm && m < eh * 60 + em;
}

export function slaMinutes(ctx: Pick<Ctx, "workspace">, kind: string, priority = "normal") {
  const s = settings(ctx).sla ?? {};
  const base = kind === "review" ? s.review ?? 1440 : kind === "comment_thread" ? s.comment ?? 60 : s.dm ?? 15;
  return priority === "urgent" ? Math.ceil(base / 4) : priority === "high" ? Math.ceil(base / 2) : base;
}

function slaDue(ctx: Pick<Ctx, "workspace">, kind: string, priority: string, from = new Date()) {
  return addBusinessMinutes(from, slaMinutes(ctx, kind, priority), ctx.workspace.timezone, settings(ctx).hours);
}

/* ------------------------------------------------------------------ */
/* Identity (spec §4)                                                   */
/* ------------------------------------------------------------------ */

export async function resolveSocialContact(ctx: Ctx, platform: Platform, authorId: string | undefined, name?: string, handle?: string) {
  const ws = ctx.workspace.id;
  const type = IDENTITY_TYPE[platform];
  if (authorId) {
    const id = await ctx.db.query.identities.findFirst({ where: and(eq(schema.identities.workspaceId, ws), eq(schema.identities.type, type), eq(schema.identities.valueNormalized, authorId)) });
    if (id) {
      const c = await ctx.db.query.contacts.findFirst({ where: eq(schema.contacts.id, id.contactId) });
      if (c && !c.deletedAt) return { contact: c, isNew: false };
      if (c?.mergedIntoId) { const s = await ctx.db.query.contacts.findFirst({ where: eq(schema.contacts.id, c.mergedIntoId) }); if (s) return { contact: s, isNew: false }; }
    }
  }
  // lightweight contact — never matched by name alone (spec §4)
  const parts = (name ?? handle ?? "Social user").trim().split(/\s+/);
  const [c] = await ctx.db.insert(schema.contacts).values({
    workspaceId: ws, firstName: parts[0] ?? null, lastName: parts.slice(1).join(" ") || null, lifecycleStage: "social_engager", source: CHANNEL_FOR[platform],
    socialIds: { ...(authorId ? { [platform]: authorId } : {}), ...(handle ? { [`${platform}_handle`]: handle } : {}) }, lastActivityAt: new Date(),
  }).returning();
  if (authorId) await ctx.db.insert(schema.identities).values({ workspaceId: ws, contactId: c!.id, type, valueNormalized: authorId }).onConflictDoNothing();
  await emit(ctx.db, ws, "contact.created", { contact_id: c!.id, source: CHANNEL_FOR[platform], lifecycle_stage: "social_engager" });
  return { contact: c!, isNew: true };
}

/** SOC-042: phones/emails posted in comments/DMs attach to the contact (no marketing consent implied); merge when they match another contact. */
export async function attachIdentifiers(ctx: Ctx, contactId: string, phones: string[], emails: string[]) {
  let current = contactId;
  const ws = ctx.workspace.id;
  for (const [type, values] of [["phone", phones], ["email", emails]] as const) {
    for (const v of values) {
      const id = await ctx.db.query.identities.findFirst({ where: and(eq(schema.identities.workspaceId, ws), eq(schema.identities.type, type), eq(schema.identities.valueNormalized, v)) });
      if (id && id.contactId !== current) {
        const { mergeContacts } = await import("./contacts");
        const other = await ctx.db.query.contacts.findFirst({ where: eq(schema.contacts.id, id.contactId) });
        if (other && !other.deletedAt) { await mergeContacts(ctx, other.id, current, `auto: ${type} shared in social message`); current = other.id; }
        continue;
      }
      if (!id) {
        await ctx.db.insert(schema.identities).values({ workspaceId: ws, contactId: current, type, valueNormalized: v }).onConflictDoNothing();
        const c = (await ctx.db.query.contacts.findFirst({ where: eq(schema.contacts.id, current) }))!;
        await ctx.db.update(schema.contacts).set(type === "phone" ? { phones: [...new Set([...c.phones, v])] } : { emails: [...new Set([...c.emails, v])] }).where(eq(schema.contacts.id, current));
      }
    }
  }
  return current;
}

/* ------------------------------------------------------------------ */
/* Ingestion (SOC-002…010)                                              */
/* ------------------------------------------------------------------ */

async function ensureObject(ctx: Ctx, account: Account, o: NormComment["object"]) {
  if (!o.externalId) return null;
  const ex = await ctx.db.query.socialObjects.findFirst({ where: and(eq(schema.socialObjects.socialAccountId, account.id), eq(schema.socialObjects.externalId, o.externalId)) });
  let adId: string | null = null, campaignId: string | null = null, campaignName = o.campaignName ?? null;
  if (o.externalAdId && !ex?.adId) {
    const ad = await ctx.db.select({ id: schema.ads.id, campaignId: schema.campaigns.id, campaignName: schema.campaigns.name }).from(schema.ads).innerJoin(schema.adSets, eq(schema.adSets.id, schema.ads.adSetId)).innerJoin(schema.campaigns, eq(schema.campaigns.id, schema.adSets.campaignId))
      .where(and(eq(schema.ads.workspaceId, ctx.workspace.id), eq(schema.ads.externalId, o.externalAdId))).limit(1);
    if (ad[0]) { adId = ad[0].id; campaignId = ad[0].campaignId; campaignName = ad[0].campaignName; }
  }
  if (ex) {
    if ((o.caption && !ex.captionExcerpt) || (o.externalAdId && !ex.externalAdId) || (o.thumbnailUrl && !ex.thumbnailUrl)) {
      const [u] = await ctx.db.update(schema.socialObjects).set({ captionExcerpt: ex.captionExcerpt ?? o.caption ?? null, thumbnailUrl: ex.thumbnailUrl ?? o.thumbnailUrl ?? null, permalink: ex.permalink ?? o.permalink ?? null,
        ...(o.externalAdId && !ex.externalAdId ? { type: "ad", externalAdId: o.externalAdId, adId, campaignId, campaignName } : {}), updatedAt: new Date() }).where(eq(schema.socialObjects.id, ex.id)).returning();
      return u!;
    }
    return ex;
  }
  const [row] = await ctx.db.insert(schema.socialObjects).values({
    workspaceId: ctx.workspace.id, socialAccountId: account.id, type: o.externalAdId ? "ad" : o.type, externalId: o.externalId, permalink: o.permalink ?? null, thumbnailUrl: o.thumbnailUrl ?? null,
    captionExcerpt: o.caption?.slice(0, 280) ?? null, externalAdId: o.externalAdId ?? null, adId, campaignId, campaignName, publishedAt: o.publishedAt ? new Date(o.publishedAt) : null,
  }).onConflictDoNothing().returning();
  return row ?? (await ctx.db.query.socialObjects.findFirst({ where: and(eq(schema.socialObjects.socialAccountId, account.id), eq(schema.socialObjects.externalId, o.externalId)) }))!;
}

async function upsertWindow(ctx: Ctx, contactId: string, channel: string, accountId: string | null, at: Date, privateReplyUntil?: Date) {
  const vals = { lastInboundAt: at, windowExpiresAt: new Date(at.getTime() + DM_WINDOW_HOURS * 3600000), socialAccountId: accountId, updatedAt: new Date(), ...(privateReplyUntil ? { privateReplyAvailableUntil: privateReplyUntil } : {}) };
  await ctx.db.insert(schema.messagingWindows).values({ workspaceId: ctx.workspace.id, contactId, channel, ...vals }).onConflictDoUpdate({ target: [schema.messagingWindows.workspaceId, schema.messagingWindows.contactId, schema.messagingWindows.channel], set: vals });
}

export type IngestResult = { status: "created" | "duplicate" | "updated" | "own" | "ignored"; commentId?: string; conversationId?: string };

export async function ingestComment(ctx: Ctx, account: Account, n: NormComment, opts: { source?: "webhook" | "backfill" | "poll" | "simulate"; runRules?: boolean } = {}): Promise<IngestResult> {
  const ws = ctx.workspace.id;
  const channel = CHANNEL_FOR[account.platform as Platform];
  const runRules = opts.runRules ?? opts.source !== "backfill";

  // 1. dedupe / edits / deletions (SOC-008)
  const existing = await ctx.db.query.comments.findFirst({ where: and(eq(schema.comments.workspaceId, ws), eq(schema.comments.channel, channel), eq(schema.comments.externalCommentId, n.commentId)) });
  if (existing) {
    if (n.verb === "edited" && n.body && n.body !== existing.body) {
      await ctx.db.update(schema.comments).set({ body: n.body, editHistory: [...existing.editHistory, { body: existing.body, at: new Date().toISOString() }], updatedAt: new Date() }).where(eq(schema.comments.id, existing.id));
      return { status: "updated", commentId: existing.id, conversationId: existing.conversationId };
    }
    if (n.verb === "remove") { await ctx.db.update(schema.comments).set({ isDeleted: true, updatedAt: new Date() }).where(eq(schema.comments.id, existing.id)); await emit(ctx.db, ws, "comment.deleted", { comment_id: existing.id, by: "platform" }); return { status: "updated", commentId: existing.id }; }
    if (n.verb === "hide" || n.verb === "unhide") { await ctx.db.update(schema.comments).set({ isHidden: n.verb === "hide", updatedAt: new Date() }).where(eq(schema.comments.id, existing.id)); return { status: "updated", commentId: existing.id }; }
    return { status: "duplicate", commentId: existing.id, conversationId: existing.conversationId };
  }
  if (n.verb === "remove" || n.verb === "hide" || n.verb === "unhide") return { status: "ignored" };

  // 2. store: object + thread grouping (SOC-009) + own-page filter (SOC-010)
  const object = await ensureObject(ctx, account, n.object);
  const own = !!n.authorId && n.authorId === account.externalAccountId;
  const threadKey = n.parentId ?? n.commentId;
  let conv: Conversation | undefined;
  if (n.parentId) {
    const parent = await ctx.db.query.comments.findFirst({ where: and(eq(schema.comments.workspaceId, ws), eq(schema.comments.channel, channel), eq(schema.comments.externalCommentId, n.parentId)) });
    if (parent) conv = await ctx.db.query.conversations.findFirst({ where: eq(schema.conversations.id, parent.conversationId) });
  }
  conv ??= await ctx.db.query.conversations.findFirst({ where: and(eq(schema.conversations.workspaceId, ws), eq(schema.conversations.channel, channel), eq(schema.conversations.externalThreadId, threadKey)) });
  const createdAt = n.createdAt ? new Date(n.createdAt) : new Date();

  if (own) {
    if (!conv) return { status: "own" };
    const [row] = await ctx.db.insert(schema.comments).values({ workspaceId: ws, conversationId: conv.id, socialObjectId: object?.id ?? null, channel, externalCommentId: n.commentId, parentExternalCommentId: n.parentId ?? null, authorExternalId: n.authorId, authorName: account.name, direction: "outbound", body: n.body, externalCreatedAt: createdAt, providerStatus: "sent" }).onConflictDoNothing().returning();
    if (row && !conv.firstResponseAt) await ctx.db.update(schema.conversations).set({ firstResponseAt: createdAt, handledBy: "human", slaDueAt: null }).where(eq(schema.conversations.id, conv.id));
    return { status: "own", commentId: row?.id, conversationId: conv.id };
  }

  // 3. identity
  const blocked = n.authorId ? await ctx.db.query.socialBlocklist.findFirst({ where: and(eq(schema.socialBlocklist.workspaceId, ws), eq(schema.socialBlocklist.platform, account.platform), eq(schema.socialBlocklist.authorExternalId, n.authorId)) }) : null;
  const { contact: c0, isNew } = await resolveSocialContact(ctx, account.platform as Platform, n.authorId, n.authorName, n.authorHandle);
  const cls = classify(n.body, { defaultCountry: ctx.workspace.settings?.defaultCountryCode, extraProfanity: settings(ctx).moderation?.blockedWords });
  const contactId = cls.phones.length || cls.emails.length ? await attachIdentifiers(ctx, c0.id, cls.phones, cls.emails) : c0.id;
  const priority = cls.urgency === "high" ? "high" : "normal";

  if (!conv) {
    const [c] = await ctx.db.insert(schema.conversations).values({
      workspaceId: ws, contactId, channel, kind: "comment_thread", socialAccountId: account.id, socialObjectId: object?.id ?? null, externalThreadId: threadKey,
      status: "open", priority, sentiment: cls.sentiment, intent: cls.intent, lastMessageAt: createdAt, lastInboundAt: createdAt, unread: 1,
      slaDueAt: opts.source === "backfill" ? null : slaDue(ctx, "comment_thread", priority, createdAt), assigneeId: null,
    }).onConflictDoNothing().returning();
    conv = c ?? (await ctx.db.query.conversations.findFirst({ where: and(eq(schema.conversations.workspaceId, ws), eq(schema.conversations.channel, channel), eq(schema.conversations.externalThreadId, threadKey)) }))!;
  } else {
    const reopen = ["resolved", "closed", "snoozed"].includes(conv.status);
    const [u] = await ctx.db.update(schema.conversations).set({
      lastMessageAt: createdAt, lastInboundAt: createdAt, unread: sql`${schema.conversations.unread} + 1`, sentiment: cls.sentiment, intent: cls.intent ?? conv.intent,
      ...(reopen ? { status: "open", snoozedUntil: null, resolvedAt: null } : {}), ...(!conv.slaDueAt && opts.source !== "backfill" ? { slaDueAt: slaDue(ctx, "comment_thread", priority, createdAt), firstResponseAt: null } : {}), updatedAt: new Date(),
    }).where(eq(schema.conversations.id, conv.id)).returning();
    conv = u!;
  }
  const [comment] = await ctx.db.insert(schema.comments).values({
    workspaceId: ws, conversationId: conv.id, socialObjectId: object?.id ?? null, channel, externalCommentId: n.commentId, parentExternalCommentId: n.parentId ?? null,
    authorExternalId: n.authorId ?? null, authorName: n.authorName ?? null, authorHandle: n.authorHandle ?? null, contactId, direction: "inbound", body: n.body,
    sentiment: cls.sentiment, intent: cls.intent, language: cls.language, toxicity: cls.toxicity, externalCreatedAt: createdAt,
  }).onConflictDoNothing().returning();
  if (!comment) return { status: "duplicate" };
  await ctx.db.update(schema.contacts).set({ lastActivityAt: createdAt }).where(eq(schema.contacts.id, contactId));
  await ctx.db.insert(schema.events).values({ workspaceId: ws, contactId, name: "social.comment", source: channel, properties: { comment_id: comment.id, object: object?.captionExcerpt ?? null, ad_id: object?.externalAdId ?? null, intent: cls.intent }, occurredAt: createdAt });
  if (account.platform === "facebook" || account.platform === "instagram") await upsertWindow(ctx, contactId, account.platform === "facebook" ? "messenger" : "instagram", account.id, createdAt, new Date(createdAt.getTime() + PRIVATE_REPLY_DAYS * 86400000));
  await ctx.db.update(schema.socialAccounts).set({ lastEventAt: new Date() }).where(eq(schema.socialAccounts.id, account.id));
  await emit(ctx.db, ws, "comment.received", { comment_id: comment.id, conversation_id: conv.id, channel, body: n.body, author: n.authorName ?? n.authorHandle, object_id: object?.externalId ?? null, ad_id: object?.externalAdId ?? null, intent: cls.intent, sentiment: cls.sentiment });
  if (!runRules) return { status: "created", commentId: comment.id, conversationId: conv.id };

  // 4–6. blocklist → moderation → classification-driven rules → routing
  if (blocked) await moderateComment(ctx, comment.id, "hide", { type: "rule", name: "Blocklist" }, `Author blocked: ${blocked.reason ?? ""}`).catch(() => {});
  else await evaluateRules(ctx, { trigger: "new_comment", conversation: conv, comment, contactId, account, objectId: object?.id ?? null, text: n.body, cls, isNewContact: isNew });
  if (settings(ctx).ai?.classify !== false) await enqueue(ctx.db, "social.ai.classify", { workspaceId: ws, commentId: comment.id }, { workspaceId: ws, maxAttempts: 2 });
  await postIngest(ctx, conv.id, cls, object?.id ?? null);
  return { status: "created", commentId: comment.id, conversationId: conv.id };
}

export async function ingestReview(ctx: Ctx, account: Account, r: NormReview, opts: { source?: string; runRules?: boolean } = {}): Promise<IngestResult> {
  const ws = ctx.workspace.id;
  const ex = await ctx.db.query.reviews.findFirst({ where: and(eq(schema.reviews.socialAccountId, account.id), eq(schema.reviews.externalReviewId, r.reviewId)) });
  if (ex) {
    if (r.body !== undefined && r.body !== ex.body) await ctx.db.update(schema.reviews).set({ body: r.body ?? null, rating: r.rating, updatedAt: new Date() }).where(eq(schema.reviews.id, ex.id));
    return { status: "duplicate", conversationId: ex.conversationId };
  }
  const { contact, isNew } = await resolveSocialContact(ctx, "google_business", `review:${r.reviewId}`, r.reviewerName);
  const cls = classify(r.body ?? "");
  const createdAt = r.createdAt ? new Date(r.createdAt) : new Date();
  const priority = r.rating <= 2 ? "high" : "normal";
  const replied = !!r.replyBody;
  const [conv] = await ctx.db.insert(schema.conversations).values({
    workspaceId: ws, contactId: contact.id, channel: "google_review", kind: "review", socialAccountId: account.id, externalThreadId: r.reviewId, status: replied ? "resolved" : "open", priority,
    sentiment: r.rating <= 2 ? "negative" : r.rating >= 4 ? "positive" : "neutral", intent: r.rating <= 2 ? "complaint" : cls.intent, lastMessageAt: createdAt, lastInboundAt: createdAt, unread: replied ? 0 : 1,
    slaDueAt: replied || opts.source === "backfill" ? null : slaDue(ctx, "review", priority, createdAt), firstResponseAt: replied ? createdAt : null, resolvedAt: replied ? createdAt : null,
  }).onConflictDoNothing().returning();
  if (!conv) return { status: "duplicate" };
  const [rev] = await ctx.db.insert(schema.reviews).values({ workspaceId: ws, conversationId: conv.id, socialAccountId: account.id, externalReviewId: r.reviewId, reviewerName: r.reviewerName ?? null, rating: r.rating, body: r.body ?? null, language: cls.language, externalCreatedAt: createdAt, replyBody: r.replyBody ?? null, replyStatus: replied ? "published" : "none", repliedAt: replied ? createdAt : null }).returning();
  await emit(ctx.db, ws, "review.received", { review_id: rev!.id, conversation_id: conv.id, rating: r.rating, body: r.body, location: account.name });
  if (opts.runRules === false || opts.source === "backfill") return { status: "created", conversationId: conv.id };
  // SOC-061 low rating alert + SOC-AI-008 draft for approval
  if (r.rating <= 2) {
    await notifyAdmins(ctx, "alert", `${r.rating}★ Google review — ${account.name}`, (r.body ?? "").slice(0, 160), `/inbox?c=${conv.id}`, ["workspace_admin", "marketing_manager"]);
    await enqueue(ctx.db, "social.ai.review_draft", { workspaceId: ws, reviewId: rev!.id }, { workspaceId: ws, maxAttempts: 2 });
  }
  await evaluateRules(ctx, { trigger: "new_review", conversation: conv, review: rev!, contactId: contact.id, account, objectId: null, text: r.body ?? "", cls, rating: r.rating, isNewContact: isNew });
  await postIngest(ctx, conv.id, cls, null);
  return { status: "created", conversationId: conv.id };
}

/** Applied to every inbound DM (WhatsApp, Messenger, IG DM, SMS, email) — windows, SLA, routing, rules parity (SOC gap table). */
export async function onInboundDm(ctx: Ctx, conversationId: string, contactId: string, text: string, isNewContact: boolean) {
  const conv = (await ctx.db.query.conversations.findFirst({ where: eq(schema.conversations.id, conversationId) }))!;
  const now = new Date();
  const cls = classify(text, { defaultCountry: ctx.workspace.settings?.defaultCountryCode, extraProfanity: settings(ctx).moderation?.blockedWords });
  if (cls.phones.length || cls.emails.length) await attachIdentifiers(ctx, contactId, cls.phones, cls.emails);
  const priority = cls.urgency === "high" ? "high" : conv.priority;
  await ctx.db.update(schema.conversations).set({
    kind: conv.kind ?? "dm", lastInboundAt: now, sentiment: cls.sentiment, intent: cls.intent ?? conv.intent, priority,
    ...(["resolved", "snoozed"].includes(conv.status) ? { status: "open", snoozedUntil: null, resolvedAt: null } : {}),
    ...(!conv.slaDueAt || conv.firstResponseAt ? { slaDueAt: slaDue(ctx, "dm", priority, now), firstResponseAt: null, slaBreachedAt: null } : {}),
  }).where(eq(schema.conversations.id, conv.id));
  if (["whatsapp", "messenger", "instagram"].includes(conv.channel)) await upsertWindow(ctx, contactId, conv.channel, conv.socialAccountId, now);
  const fresh = (await ctx.db.query.conversations.findFirst({ where: eq(schema.conversations.id, conv.id) }))!;
  await evaluateRules(ctx, { trigger: "new_dm", conversation: fresh, contactId, account: null, objectId: null, text, cls, isNewContact });
  await postIngest(ctx, conv.id, cls, null);
  // SOC-AI-009 handoff on request / negative sentiment while the AI agent is active
  if (fresh.aiAgentActive && (/\b(talk to|speak to|real|human|person|agent|manager)\b.*\b(person|human|agent|someone|manager)?|মানুষ|কারো সাথে কথা/i.test(text) && /\b(talk|speak|human|person|agent|manager)\b|মানুষ/i.test(text) || cls.sentiment === "negative")) {
    await handoffToHuman(ctx, conv.id, cls.sentiment === "negative" ? "Negative sentiment detected" : "Customer asked for a person");
  }
}

export async function handoffToHuman(ctx: Ctx, conversationId: string, reason: string) {
  const conv = (await ctx.db.query.conversations.findFirst({ where: eq(schema.conversations.id, conversationId) }))!;
  let assignee = conv.assigneeId;
  if (!assignee) assignee = await pickAgent(ctx, { team: null, userIds: [] });
  await ctx.db.update(schema.conversations).set({ aiAgentActive: false, assigneeId: assignee, status: "open", priority: "high" }).where(eq(schema.conversations.id, conversationId));
  await ctx.db.insert(schema.messages).values({ workspaceId: ctx.workspace.id, conversationId, direction: "note", channel: conv.channel, body: `🤖→👤 AI handed off: ${reason}`, status: "sent" });
  if (assignee) await notifyUser(ctx, assignee, "message", "AI handed a conversation to you", reason, `/inbox?c=${conversationId}`);
}

/** Routing + notification + spike/negative alerts after rules. */
async function postIngest(ctx: Ctx, conversationId: string, cls: Classification, objectId: string | null) {
  const conv = (await ctx.db.query.conversations.findFirst({ where: eq(schema.conversations.id, conversationId) }))!;
  if (!conv.assigneeId) {
    const contact = await ctx.db.query.contacts.findFirst({ where: eq(schema.contacts.id, conv.contactId) });
    const owner = contact?.ownerId && (await isAvailable(ctx, contact.ownerId)) ? contact.ownerId : null;
    if (owner) await assignConversation(ctx, conv.id, owner, { type: "rule", name: "Contact owner" });
  } else await notifyUser(ctx, conv.assigneeId, "message", `New ${conv.kind === "comment_thread" ? "comment" : conv.kind === "review" ? "review" : "message"}`, undefined, `/inbox?c=${conv.id}`);
  // SOC-061 alerts
  if (cls.intent === "complaint" || /\b(fraud|scam|complaint)\b|প্রতারণা|বাটপার|অভিযোগ/i.test(String(cls.intent)) ) {
    await notifyAdmins(ctx, "alert", `Complaint on ${conv.channel.replace("_", " ")}`, "A customer complaint needs attention", `/inbox?c=${conv.id}`, ["workspace_admin", "marketing_manager"]);
  }
  if (objectId) {
    const threshold = settings(ctx).spikeThreshold ?? 20;
    const [{ n }] = (await ctx.db.select({ n: sql<number>`count(*)::int` }).from(schema.comments).where(and(eq(schema.comments.socialObjectId, objectId), eq(schema.comments.direction, "inbound"), gte(schema.comments.externalCreatedAt, new Date(Date.now() - 30 * 60000))))) as [{ n: number }];
    if (n === threshold) {
      const obj = await ctx.db.query.socialObjects.findFirst({ where: eq(schema.socialObjects.id, objectId) });
      await notifyAdmins(ctx, "alert", "Comment spike", `${n} comments in 30 min on “${obj?.captionExcerpt?.slice(0, 60) ?? "a post"}”`, `/inbox?object=${objectId}`, ["workspace_admin", "marketing_manager"]);
    }
  }
}

/* ------------------------------------------------------------------ */
/* Routing (SOC-070, SOC-073)                                           */
/* ------------------------------------------------------------------ */

async function isAvailable(ctx: Pick<Ctx, "db" | "workspace">, userId: string) {
  const m = await ctx.db.query.memberships.findFirst({ where: and(eq(schema.memberships.workspaceId, ctx.workspace.id), eq(schema.memberships.userId, userId)) });
  return !!m && m.active && m.availability !== "away";
}

/** Round-robin within a team (or given users), skipping away agents; least open conversations first. */
export async function pickAgent(ctx: Ctx, opts: { team?: string | null; userIds?: string[] }) {
  const members = await ctx.db.select().from(schema.memberships).where(and(eq(schema.memberships.workspaceId, ctx.workspace.id), eq(schema.memberships.active, true)));
  let pool = members.filter((m) => m.availability !== "away" && (opts.userIds?.length ? opts.userIds.includes(m.userId) : opts.team ? m.team === opts.team : true));
  if (!pool.length) return null;
  const loads = await ctx.db.select({ a: schema.conversations.assigneeId, n: sql<number>`count(*)::int` }).from(schema.conversations)
    .where(and(eq(schema.conversations.workspaceId, ctx.workspace.id), inArray(schema.conversations.status, ["open", "pending"]), inArray(schema.conversations.assigneeId, pool.map((p) => p.userId)))).groupBy(schema.conversations.assigneeId);
  const map = new Map(loads.map((l) => [l.a, l.n]));
  pool = pool.sort((x, y) => (map.get(x.userId) ?? 0) - (map.get(y.userId) ?? 0));
  return pool[0]!.userId;
}

export async function assignConversation(ctx: Ctx, conversationId: string, userId: string | null, by: By) {
  const [c] = await ctx.db.update(schema.conversations).set({ assigneeId: userId, updatedAt: new Date() }).where(and(eq(schema.conversations.id, conversationId), eq(schema.conversations.workspaceId, ctx.workspace.id))).returning();
  if (!c) throw new ApiError(404, "not_found", "Conversation not found");
  if (userId) await notifyUser(ctx, userId, "message", `Assigned to you: ${c.kind === "comment_thread" ? "comment" : c.kind === "review" ? "review" : "conversation"}`, by.name ? `by ${by.name}` : undefined, `/inbox?c=${c.id}`);
  await audit({ ...ctx, actor: actorOf(ctx, by) }, "assign", "conversation", c.id, undefined, { assignee: userId });
  await emit(ctx.db, ctx.workspace.id, "conversation.assigned", { conversation_id: c.id, assignee_id: userId, by: by.type });
  return c;
}

function actorOf(ctx: Ctx, by: By): Ctx["actor"] {
  if (by.type === "user") return ctx.actor;
  return { type: by.type === "ai" ? "agent" : "system", id: by.ruleId ?? (by.type === "ai" ? "social-ai" : null), name: by.name ?? (by.type === "ai" ? "Social AI" : "Engagement rule") };
}

/* ------------------------------------------------------------------ */
/* Replying & moderation (SOC-030…037)                                  */
/* ------------------------------------------------------------------ */

async function loadComment(ctx: Ctx, id: string) {
  const c = await ctx.db.query.comments.findFirst({ where: and(eq(schema.comments.id, id), eq(schema.comments.workspaceId, ctx.workspace.id)) });
  if (!c) throw new ApiError(404, "not_found", "Comment not found");
  const conv = (await ctx.db.query.conversations.findFirst({ where: eq(schema.conversations.id, c.conversationId) }))!;
  const account = conv.socialAccountId ? await getAccount(ctx, conv.socialAccountId) : null;
  if (!account) throw new ApiError(409, "conflict", "Comment is not linked to a social account");
  const object = c.socialObjectId ? await ctx.db.query.socialObjects.findFirst({ where: eq(schema.socialObjects.id, c.socialObjectId) }) : null;
  return { comment: c, conv, account, object };
}

async function markResponded(ctx: Ctx, conv: Conversation, by: By) {
  await ctx.db.update(schema.conversations).set({
    firstResponseAt: conv.firstResponseAt ?? new Date(), handledBy: conv.handledBy ?? by.type === "user" ? (conv.handledBy ?? "human") : conv.handledBy ?? by.type,
    slaDueAt: null, unread: 0, status: conv.status === "open" ? "pending" : conv.status, lastMessageAt: new Date(), updatedAt: new Date(),
  }).where(eq(schema.conversations.id, conv.id));
}

async function renderReply(ctx: Ctx, contactId: string | null, body: string, objectId?: string | null) {
  const contact = contactId ? await ctx.db.query.contacts.findFirst({ where: eq(schema.contacts.id, contactId) }) : null;
  const obj = objectId ? await ctx.db.query.socialObjects.findFirst({ where: eq(schema.socialObjects.id, objectId) }) : null;
  return renderTemplate(body, { first_name: contact?.firstName, last_name: contact?.lastName, name: contact ? fullName(contact) : "", project: contact?.project, project_name: contact?.project ?? obj?.campaignName, workspace: ctx.workspace.name, custom: contact?.customFields ?? {} }).trim();
}

export async function replyToComment(ctx: Ctx, commentId: string, rawBody: string, by: By) {
  const { comment, conv, account, object } = await loadComment(ctx, commentId);
  if (by.type === "user") await assertConversationAccess(ctx, conv, "reply");
  const body = await renderReply(ctx, comment.contactId, rawBody, object?.id);
  if (!body) throw new ApiError(422, "validation_failed", "Reply is empty");
  const target = comment.direction === "inbound" ? comment : null;
  const integration = await integrationOf(ctx, account);
  const [row] = await ctx.db.insert(schema.comments).values({ workspaceId: ctx.workspace.id, conversationId: conv.id, socialObjectId: comment.socialObjectId, channel: comment.channel, externalCommentId: `pending_${crypto.randomUUID()}`, parentExternalCommentId: target?.parentExternalCommentId ?? target?.externalCommentId ?? null, authorName: account.name, authorExternalId: account.externalAccountId, direction: "outbound", body, sentByUserId: by.type === "user" ? by.userId ?? null : null, sentByAi: by.type === "ai", sentByRuleId: by.ruleId ?? null, providerStatus: "queued" }).returning();
  try {
    const r = await act(ctx, integration, account, "reply", { commentId: (target?.parentExternalCommentId && account.platform !== "facebook" ? target.parentExternalCommentId : target?.externalCommentId) ?? comment.externalCommentId, body, objectId: object?.externalId });
    const [u] = await ctx.db.update(schema.comments).set({ externalCommentId: r.id ?? row!.externalCommentId, providerStatus: "sent" }).where(eq(schema.comments.id, row!.id)).returning();
    await markResponded(ctx, conv, by);
    await audit({ ...ctx, actor: actorOf(ctx, by) }, "social.reply", "comment", comment.id, undefined, { body, reply_id: u!.id });
    await emit(ctx.db, ctx.workspace.id, "comment.replied", { comment_id: comment.id, reply_id: u!.id, conversation_id: conv.id, body, by: by.type });
    return u!;
  } catch (e) {
    await failSend(ctx, row!.id, integration?.id ?? null, e);
    throw new ApiError(502, "send_failed", (e as Error).message, { comment_id: row!.id });
  }
}

/** SOC-036: surface provider errors in the thread and flag the integration when the token is the problem. */
async function failSend(ctx: Ctx, outboundCommentId: string, integrationId: string | null, e: unknown) {
  const msg = e instanceof Error ? e.message : String(e);
  await ctx.db.update(schema.comments).set({ providerStatus: "failed", providerError: msg.slice(0, 500) }).where(eq(schema.comments.id, outboundCommentId));
  if (integrationId && /token|expired|OAuth|permission|401|190/i.test(msg)) {
    await ctx.db.update(schema.integrations).set({ status: "expired", lastError: msg.slice(0, 500) }).where(eq(schema.integrations.id, integrationId));
    await ctx.db.update(schema.socialAccounts).set({ status: "error", lastError: msg.slice(0, 500) }).where(eq(schema.socialAccounts.integrationId, integrationId));
  }
}

export async function retrySend(ctx: Ctx, outboundCommentId: string, by: By) {
  const c = await ctx.db.query.comments.findFirst({ where: and(eq(schema.comments.id, outboundCommentId), eq(schema.comments.workspaceId, ctx.workspace.id)) });
  if (!c || c.direction !== "outbound" || c.providerStatus !== "failed") throw new ApiError(409, "conflict", "Only failed replies can be retried");
  const parent = await ctx.db.query.comments.findFirst({ where: and(eq(schema.comments.workspaceId, ctx.workspace.id), eq(schema.comments.channel, c.channel), eq(schema.comments.externalCommentId, c.parentExternalCommentId ?? "")) });
  await ctx.db.delete(schema.comments).where(eq(schema.comments.id, c.id));
  return replyToComment(ctx, parent?.id ?? c.id, c.body, by);
}

export async function privateReply(ctx: Ctx, commentId: string, rawBody: string, by: By) {
  const { comment, conv, account, object } = await loadComment(ctx, commentId);
  if (by.type === "user") await assertConversationAccess(ctx, conv, "reply");
  if (comment.direction !== "inbound") throw new ApiError(422, "validation_failed", "Private replies go to the commenter — choose their comment");
  const dmChannel = account.platform === "facebook" ? "messenger" : account.platform === "instagram" ? "instagram" : null;
  if (!dmChannel) throw new ApiError(422, "unsupported", `${account.platform} doesn't support private replies`);
  if (!comment.contactId) throw new ApiError(409, "conflict", "Commenter unknown");
  const win = await ctx.db.query.messagingWindows.findFirst({ where: and(eq(schema.messagingWindows.workspaceId, ctx.workspace.id), eq(schema.messagingWindows.contactId, comment.contactId), eq(schema.messagingWindows.channel, dmChannel)) });
  const until = win?.privateReplyAvailableUntil ?? new Date(comment.externalCreatedAt.getTime() + PRIVATE_REPLY_DAYS * 86400000);
  if (until < new Date()) throw new ApiError(422, "window_closed", `Private replies are only allowed within ${PRIVATE_REPLY_DAYS} days of the comment`);
  const already = await ctx.db.query.events.findFirst({ where: and(eq(schema.events.workspaceId, ctx.workspace.id), eq(schema.events.name, "social.private_reply"), sql`${schema.events.properties}->>'comment_id' = ${comment.id}`) });
  if (already) throw new ApiError(409, "already_sent", "This commenter already received a private reply for this comment (platform limit: one)");
  const body = await renderReply(ctx, comment.contactId, rawBody, object?.id);
  const integration = await integrationOf(ctx, account);
  const r = await act(ctx, integration, account, "private_reply", { commentId: comment.externalCommentId, body }).catch((e) => { throw new ApiError(502, "send_failed", (e as Error).message); });
  // create / link the DM conversation (SOC-031)
  const contact = (await ctx.db.query.contacts.findFirst({ where: eq(schema.contacts.id, comment.contactId) }))!;
  const { getOrCreateConversation } = await import("./messaging");
  const dm = await getOrCreateConversation(ctx, contact, dmChannel, "pending");
  await ctx.db.update(schema.conversations).set({ kind: "dm", socialAccountId: account.id, tags: [...new Set([...(dm.tags ?? []), `from_comment:${conv.id}`])], lastMessageAt: new Date() }).where(eq(schema.conversations.id, dm.id));
  await ctx.db.insert(schema.messages).values({ workspaceId: ctx.workspace.id, conversationId: dm.id, direction: "out", channel: dmChannel, body, status: "sent", providerMessageId: r.id ?? null, senderId: by.type === "user" ? by.userId ?? null : null });
  await ctx.db.insert(schema.events).values({ workspaceId: ctx.workspace.id, contactId: contact.id, name: "social.private_reply", source: dmChannel, properties: { comment_id: comment.id, conversation_id: dm.id } });
  await ctx.db.update(schema.conversations).set({ tags: [...new Set([...(conv.tags ?? []), "private_replied"])] }).where(eq(schema.conversations.id, conv.id));
  await markResponded(ctx, conv, by);
  await audit({ ...ctx, actor: actorOf(ctx, by) }, "social.private_reply", "comment", comment.id, undefined, { body, dm_conversation: dm.id });
  return { dmConversationId: dm.id, providerMessageId: r.id };
}

export async function moderateComment(ctx: Ctx, commentId: string, action: "hide" | "unhide" | "delete" | "like" | "unlike" | "mark_spam", by: By, reason?: string) {
  const { comment, conv, account } = await loadComment(ctx, commentId);
  if (by.type === "user") {
    if (action === "like" || action === "unlike") await assertConversationAccess(ctx, conv, "reply");
    else { assertSocial(ctx, "moderate"); await assertConversationAccess(ctx, conv, "view"); }
  }
  const integration = await integrationOf(ctx, account);
  const op: SocialOp = action === "mark_spam" ? "hide" : action;
  await act(ctx, integration, account, op, { commentId: comment.externalCommentId, objectId: undefined }).catch((e) => { throw new ApiError(502, "provider_error", (e as Error).message); });
  const hiddenBy = by.type === "user" ? `user:${by.userId}` : by.type === "rule" ? `rule:${by.ruleId ?? ""}` : "ai";
  const patch: Partial<CommentRow> = action === "hide" || action === "mark_spam" ? { isHidden: true, hiddenReason: reason ?? (action === "mark_spam" ? "spam" : null), hiddenBy } : action === "unhide" ? { isHidden: false, hiddenReason: null, hiddenBy: null } : action === "delete" ? { isDeleted: true } : { likedByPage: action === "like" };
  if (action === "mark_spam") patch.intent = "spam";
  await ctx.db.update(schema.comments).set({ ...patch, updatedAt: new Date() }).where(eq(schema.comments.id, comment.id));
  if (action !== "like" && action !== "unlike") {
    await ctx.db.insert(schema.moderationEvents).values({ workspaceId: ctx.workspace.id, commentId: comment.id, action, reason: reason ?? null, actorType: by.type, actorId: by.type === "user" ? by.userId ?? null : by.ruleId ?? null, actorName: by.type === "user" ? ctx.actor.name : by.name ?? by.type });
    if (action === "unhide") await ctx.db.update(schema.moderationEvents).set({ undoneAt: new Date() }).where(and(eq(schema.moderationEvents.commentId, comment.id), eq(schema.moderationEvents.action, "hide"), isNull(schema.moderationEvents.undoneAt)));
    if (action === "mark_spam") await ctx.db.update(schema.conversations).set({ status: "resolved", resolvedAt: new Date(), intent: "spam", slaDueAt: null }).where(eq(schema.conversations.id, conv.id));
  }
  await audit({ ...ctx, actor: actorOf(ctx, by) }, `social.${action}`, "comment", comment.id, { hidden: comment.isHidden, deleted: comment.isDeleted }, { ...patch, reason });
  if (action === "hide" || action === "mark_spam") await emit(ctx.db, ctx.workspace.id, "comment.hidden", { comment_id: comment.id, reason, by: by.type });
  if (action === "delete") await emit(ctx.db, ctx.workspace.id, "comment.deleted", { comment_id: comment.id, by: by.type });
  return { ok: true };
}

export async function undoModeration(ctx: Ctx, eventId: string) {
  assertSocial(ctx, "moderate");
  const ev = await ctx.db.query.moderationEvents.findFirst({ where: and(eq(schema.moderationEvents.id, eventId), eq(schema.moderationEvents.workspaceId, ctx.workspace.id)) });
  if (!ev) throw new ApiError(404, "not_found", "Moderation event not found");
  if (ev.undoneAt) throw new ApiError(409, "conflict", "Already undone");
  if (ev.action === "delete") throw new ApiError(422, "irreversible", "Deleted comments can't be restored on the platform");
  await moderateComment(ctx, ev.commentId, "unhide", { type: "user", userId: ctx.user?.id }, "Undo moderation");
  await ctx.db.update(schema.moderationEvents).set({ undoneAt: new Date() }).where(eq(schema.moderationEvents.id, ev.id));
}

export async function replyToReview(ctx: Ctx, reviewId: string, body: string, by: By) {
  const rev = await ctx.db.query.reviews.findFirst({ where: and(eq(schema.reviews.id, reviewId), eq(schema.reviews.workspaceId, ctx.workspace.id)) });
  if (!rev) throw new ApiError(404, "not_found", "Review not found");
  const conv = (await ctx.db.query.conversations.findFirst({ where: eq(schema.conversations.id, rev.conversationId) }))!;
  if (by.type === "user") await assertConversationAccess(ctx, conv, "reply");
  const account = await getAccount(ctx, rev.socialAccountId);
  const text = body.trim();
  if (!text) throw new ApiError(422, "validation_failed", "Reply is empty");
  try {
    await act(ctx, await integrationOf(ctx, account), account, "review_reply", { reviewId: rev.externalReviewId, body: text });
  } catch (e) {
    await ctx.db.update(schema.reviews).set({ replyStatus: "failed" }).where(eq(schema.reviews.id, rev.id));
    throw new ApiError(502, "send_failed", (e as Error).message);
  }
  const [u] = await ctx.db.update(schema.reviews).set({ replyBody: text, replyStatus: "published", repliedAt: new Date(), repliedByUserId: by.type === "user" ? by.userId ?? null : null, repliedByAi: by.type === "ai", updatedAt: new Date() }).where(eq(schema.reviews.id, rev.id)).returning();
  await markResponded(ctx, conv, by);
  await ctx.db.update(schema.conversations).set({ status: "resolved", resolvedAt: new Date() }).where(eq(schema.conversations.id, conv.id));
  await audit({ ...ctx, actor: actorOf(ctx, by) }, rev.replyBody ? "social.review_reply_edit" : "social.review_reply", "review", rev.id, { reply: rev.replyBody }, { reply: text });
  await emit(ctx.db, ctx.workspace.id, "review.replied", { review_id: rev.id, body: text, by: by.type });
  return u!;
}

/* ------------------------------------------------------------------ */
/* Lead capture (SOC-040…044) & Move to WhatsApp (SOC-035)              */
/* ------------------------------------------------------------------ */

export async function createLeadFromConversation(ctx: Ctx, conversationId: string, by: By, commentId?: string) {
  const conv = await ctx.db.query.conversations.findFirst({ where: and(eq(schema.conversations.id, conversationId), eq(schema.conversations.workspaceId, ctx.workspace.id)) });
  if (!conv) throw new ApiError(404, "not_found", "Conversation not found");
  if (by.type === "user") await assertConversationAccess(ctx, conv, "reply");
  const obj = conv.socialObjectId ? await ctx.db.query.socialObjects.findFirst({ where: eq(schema.socialObjects.id, conv.socialObjectId) }) : null;
  const comment = commentId ? await ctx.db.query.comments.findFirst({ where: eq(schema.comments.id, commentId) }) : null;
  const campaign = obj?.campaignId ? await ctx.db.query.campaigns.findFirst({ where: eq(schema.campaigns.id, obj.campaignId) }) : null;
  const adSet = obj?.adId ? await ctx.db.select({ e: schema.adSets.externalId }).from(schema.ads).innerJoin(schema.adSets, eq(schema.adSets.id, schema.ads.adSetId)).where(eq(schema.ads.id, obj.adId)).limit(1) : [];
  const { captureLead } = await import("./leads");
  const contact = (await ctx.db.query.contacts.findFirst({ where: eq(schema.contacts.id, conv.contactId) }))!;
  const r = await captureLead({ ...ctx, actor: actorOf(ctx, by) }, {
    contactId: contact.id, project: contact.project ?? undefined,
    attribution: { channel: conv.channel === "google_review" ? "google_review" : conv.channel, campaignId: campaign?.externalId ?? undefined, adsetId: adSet[0]?.e ?? undefined, adId: obj?.externalAdId ?? undefined, utmSource: conv.channel.split("_")[0], utmMedium: obj?.type === "ad" ? "paid_social_comment" : "organic_social", utmContent: obj?.externalId ?? undefined, landingUrl: obj?.permalink ?? undefined },
    note: comment ? `From ${conv.channel.replace("_", " ")}: “${comment.body.slice(0, 300)}”` : undefined,
  });
  await ctx.db.update(schema.conversations).set({ tags: [...new Set([...(conv.tags ?? []), "lead"])] }).where(eq(schema.conversations.id, conv.id));
  await ctx.db.insert(schema.events).values({ workspaceId: ctx.workspace.id, contactId: contact.id, name: "social.lead_created", source: conv.channel, properties: { conversation_id: conv.id, object_id: obj?.id ?? null, ad_id: obj?.externalAdId ?? null, by: by.type } });
  return r;
}

export async function moveToWhatsApp(ctx: Ctx, conversationId: string, by: By) {
  const conv = await ctx.db.query.conversations.findFirst({ where: and(eq(schema.conversations.id, conversationId), eq(schema.conversations.workspaceId, ctx.workspace.id)) });
  if (!conv) throw new ApiError(404, "not_found", "Conversation not found");
  if (by.type === "user") await assertConversationAccess(ctx, conv, "reply");
  const contact = (await ctx.db.query.contacts.findFirst({ where: eq(schema.contacts.id, conv.contactId) }))!;
  const { consentState } = await import("./contacts");
  const { state } = await consentState(ctx, contact.id);
  await ctx.db.update(schema.contacts).set({ tags: [...new Set([...contact.tags, `via:${conv.channel}`])] }).where(eq(schema.contacts.id, contact.id));
  if (contact.phones[0] && state.whatsapp?.status === "opted_in") {
    const tpl = await ctx.db.query.templates.findFirst({ where: and(eq(schema.templates.workspaceId, ctx.workspace.id), eq(schema.templates.channel, "whatsapp"), eq(schema.templates.providerStatus, "approved")) });
    if (!tpl) throw new ApiError(409, "no_template", "Create an approved WhatsApp template first");
    const { sendMessage } = await import("./messaging");
    const r = await sendMessage({ ...ctx, actor: actorOf(ctx, by) }, { contactId: contact.id, channel: "whatsapp", templateId: tpl.id, source: by.type === "user" ? "human" : "journey" });
    return { method: "whatsapp_template", status: r.message?.status, error: r.message?.error };
  }
  const num = (settings(ctx).whatsappNumber ?? "").replace(/[^\d]/g, "");
  if (!num) throw new ApiError(409, "not_configured", "Set your WhatsApp business number in Settings → Social to use click-to-chat");
  const link = `https://wa.me/${num}?text=${encodeURIComponent(`Hi, I'm interested (ref ${conv.id.slice(0, 8)})`)}`;
  const firstInbound = await ctx.db.query.comments.findFirst({ where: and(eq(schema.comments.conversationId, conv.id), eq(schema.comments.direction, "inbound")), orderBy: desc(schema.comments.externalCreatedAt) });
  if (conv.kind === "comment_thread" && firstInbound) {
    await privateReply(ctx, firstInbound.id, `Thanks for your interest! Chat with us on WhatsApp for prices and details: ${link}`, by);
    return { method: "private_reply_link", link };
  }
  const { sendMessage } = await import("./messaging");
  const r = await sendMessage({ ...ctx, actor: actorOf(ctx, by) }, { contactId: contact.id, channel: conv.channel, body: `Continue on WhatsApp: ${link}`, conversationId: conv.id, source: by.type === "user" ? "human" : "journey" });
  return { method: "dm_link", link, status: r.message?.status };
}

/* ------------------------------------------------------------------ */
/* Inbox actions (SOC-023…028)                                          */
/* ------------------------------------------------------------------ */

export async function setStatus(ctx: Ctx, conversationId: string, status: "open" | "pending" | "snoozed" | "resolved" | "closed", snoozedUntil?: Date) {
  const conv = await ctx.db.query.conversations.findFirst({ where: and(eq(schema.conversations.id, conversationId), eq(schema.conversations.workspaceId, ctx.workspace.id)) });
  if (!conv) throw new ApiError(404, "not_found", "Conversation not found");
  await assertConversationAccess(ctx, conv, "reply");
  if (status === "snoozed" && !snoozedUntil) throw new ApiError(422, "validation_failed", "Choose when to snooze until");
  const [u] = await ctx.db.update(schema.conversations).set({ status, snoozedUntil: status === "snoozed" ? snoozedUntil! : null, resolvedAt: status === "resolved" || status === "closed" ? new Date() : null, ...(status === "resolved" || status === "closed" ? { slaDueAt: null } : {}), updatedAt: new Date() }).where(eq(schema.conversations.id, conv.id)).returning();
  await audit(ctx, `conversation.${status}`, "conversation", conv.id, { status: conv.status }, { status, snoozedUntil });
  if (status === "resolved") {
    await emit(ctx.db, ctx.workspace.id, "conversation.resolved", { conversation_id: conv.id, by: ctx.actor.type });
    await enqueue(ctx.db, "social.ai.summary", { workspaceId: ctx.workspace.id, conversationId: conv.id }, { workspaceId: ctx.workspace.id, maxAttempts: 1 }); // SOC-AI-007
  }
  return u!;
}

export async function setTags(ctx: Ctx, conversationId: string, tags: string[]) {
  const conv = await ctx.db.query.conversations.findFirst({ where: and(eq(schema.conversations.id, conversationId), eq(schema.conversations.workspaceId, ctx.workspace.id)) });
  if (!conv) throw new ApiError(404, "not_found", "Conversation not found");
  await assertConversationAccess(ctx, conv, "reply");
  const [u] = await ctx.db.update(schema.conversations).set({ tags: [...new Set(tags.map((t) => t.trim()).filter(Boolean))], updatedAt: new Date() }).where(eq(schema.conversations.id, conv.id)).returning();
  return u!;
}

/** SOC-025: notes with @mentions notify the mentioned teammates. */
export async function addNote(ctx: Ctx, conversationId: string, body: string) {
  const conv = await ctx.db.query.conversations.findFirst({ where: and(eq(schema.conversations.id, conversationId), eq(schema.conversations.workspaceId, ctx.workspace.id)) });
  if (!conv) throw new ApiError(404, "not_found", "Conversation not found");
  await assertConversationAccess(ctx, conv, "view");
  const [m] = await ctx.db.insert(schema.messages).values({ workspaceId: ctx.workspace.id, conversationId, direction: "note", channel: conv.channel, body, status: "sent", senderId: ctx.user?.id ?? null }).returning();
  const team = await activeUsers(ctx.db, ctx.workspace.id);
  const mentioned = team.filter((u) => body.toLowerCase().includes(`@${u.name.split(" ")[0]!.toLowerCase()}`) || body.toLowerCase().includes(`@${u.name.toLowerCase().replace(/\s+/g, "")}`));
  for (const u of mentioned) if (u.id !== ctx.user?.id) await notifyUser(ctx, u.id, "mention", `${ctx.actor.name} mentioned you`, body.slice(0, 140), `/inbox?c=${conversationId}`);
  return { note: m, mentioned: mentioned.map((u) => u.id) };
}

/** SOC-026: soft lock for 2 minutes while typing; others see "X is replying". */
export async function lockConversation(ctx: Ctx, conversationId: string, release = false, force = false) {
  const conv = await ctx.db.query.conversations.findFirst({ where: and(eq(schema.conversations.id, conversationId), eq(schema.conversations.workspaceId, ctx.workspace.id)) });
  if (!conv) throw new ApiError(404, "not_found", "Conversation not found");
  const me = ctx.user?.id ?? null;
  if (release) {
    if (conv.lockedByUserId === me) await ctx.db.update(schema.conversations).set({ lockedByUserId: null, lockedUntil: null }).where(eq(schema.conversations.id, conv.id));
    return { locked: false };
  }
  const heldByOther = conv.lockedByUserId && conv.lockedByUserId !== me && conv.lockedUntil && conv.lockedUntil > new Date();
  if (heldByOther && !force) {
    const u = await ctx.db.query.users.findFirst({ where: eq(schema.users.id, conv.lockedByUserId!) });
    return { locked: false, heldBy: { id: conv.lockedByUserId, name: u?.name ?? "Someone" }, until: conv.lockedUntil };
  }
  await ctx.db.update(schema.conversations).set({ lockedByUserId: me, lockedUntil: new Date(Date.now() + 120000) }).where(eq(schema.conversations.id, conv.id));
  if (heldByOther && force) await audit(ctx, "conversation.lock_override", "conversation", conv.id, { lockedBy: conv.lockedByUserId }, { lockedBy: me });
  return { locked: true, until: new Date(Date.now() + 120000) };
}

/* ------------------------------------------------------------------ */
/* Rules engine (SOC-050…058, 060, 061, 070)                            */
/* ------------------------------------------------------------------ */

export type RuleEvent = {
  trigger: "new_comment" | "new_dm" | "new_review";
  conversation: Conversation; comment?: CommentRow; review?: typeof schema.reviews.$inferSelect; contactId: string; account: Account | null; objectId: string | null;
  text: string; cls: Classification; rating?: number; isNewContact: boolean; at?: Date;
};
export type RuleOutcome = { ruleId: string; ruleName: string; actions: { type: string; ok: boolean; detail?: string }[]; stopped: boolean };

function conditionsMatch(ctx: Pick<Ctx, "workspace">, c: RuleConditions, e: RuleEvent, contact: typeof schema.contacts.$inferSelect | undefined) {
  const text = e.text ?? "";
  if (c.keywords?.length) {
    const hits = c.keywords.map((k) => containsWord(text, [k]));
    if (c.keywordMode === "all" ? !hits.every(Boolean) : !hits.some(Boolean)) return false;
  }
  if (c.intents?.length && !c.intents.includes(e.cls.intent ?? "")) return false;
  if (c.sentiments?.length && !c.sentiments.includes(e.cls.sentiment)) return false;
  if (c.maxRating !== undefined && (e.rating === undefined || e.rating > c.maxRating)) return false;
  if (c.languages?.length && !c.languages.includes(e.cls.language)) return false;
  if (c.firstMessageFromNewContact && !e.isNewContact) return false;
  if (c.hasPhone && !e.cls.phones.length) return false;
  if (c.hasLink && !e.cls.hasLink) return false;
  if (c.profanity && !e.cls.profanity && !e.cls.spam) return false;
  if (c.competitorNames?.length && !containsWord(text, c.competitorNames)) return false;
  if (c.contactField && contact) {
    const v = c.contactField.field.startsWith("custom.") ? (contact.customFields as Record<string, unknown>)[c.contactField.field.slice(7)] : (contact as Record<string, unknown>)[c.contactField.field];
    if (String(v ?? "").toLowerCase() !== c.contactField.value.toLowerCase()) return false;
  }
  return true;
}

function scheduleMatches(ws: Ctx["workspace"], s: typeof schema.engagementRules.$inferSelect["schedule"], at: Date) {
  if (!s?.mode || s.mode === "always") return true;
  let inHours: boolean;
  if (s.start && s.end) {
    const tz = s.timezone ?? ws.timezone;
    const day = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"].indexOf(new Intl.DateTimeFormat("en-US", { timeZone: tz, weekday: "short" }).format(at));
    const m = localMinutes(at, tz);
    const [sh, sm] = s.start.split(":").map(Number) as [number, number];
    const [eh, em] = s.end.split(":").map(Number) as [number, number];
    inHours = (!s.days?.length || s.days.includes(day)) && m >= sh * 60 + sm && m < eh * 60 + em;
  } else inHours = isBusinessHours(ws, at);
  return s.mode === "in_hours" ? inHours : !inHours;
}

export async function evaluateRules(ctx: Ctx, e: RuleEvent, opts: { test?: boolean; ruleIds?: string[] } = {}): Promise<RuleOutcome[]> {
  const all = await ctx.db.select().from(schema.engagementRules).where(and(eq(schema.engagementRules.workspaceId, ctx.workspace.id), opts.test ? undefined : eq(schema.engagementRules.isActive, true)));
  // moderation always runs before replies (spec §10), then priority order
  const rules = all.filter((r) => !opts.ruleIds || opts.ruleIds.includes(r.id)).sort((a, b) => (a.type === "moderation" ? 0 : 1) - (b.type === "moderation" ? 0 : 1) || a.priority - b.priority);
  const contact = await ctx.db.query.contacts.findFirst({ where: eq(schema.contacts.id, e.contactId) });
  const at = e.at ?? new Date();
  const out: RuleOutcome[] = [];
  let hidden = false;
  for (const r of rules) {
    if (r.trigger !== "any" && r.trigger !== e.trigger) continue;
    if (r.channels.length && !r.channels.includes(e.conversation.channel)) continue;
    if (r.socialAccountIds.length && (!e.account || !r.socialAccountIds.includes(e.account.id))) continue;
    if (r.socialObjectIds.length && (!e.objectId || !r.socialObjectIds.includes(e.objectId))) continue;
    if (!scheduleMatches(ctx.workspace, r.schedule, at)) continue;
    if (!conditionsMatch(ctx, r.conditions, e, contact)) continue;
    // SOC-054 rate limits & once-per-user-per-post
    if (!opts.test) {
      if (r.rateLimit.perMinute) {
        const [{ n }] = (await ctx.db.select({ n: sql<number>`count(*)::int` }).from(schema.ruleFirings).where(and(eq(schema.ruleFirings.ruleId, r.id), gte(schema.ruleFirings.createdAt, new Date(Date.now() - 60000))))) as [{ n: number }];
        if (n >= r.rateLimit.perMinute) continue;
      }
      const author = e.comment?.authorExternalId ?? e.contactId;
      if (r.rateLimit.oncePerUserPerObject) {
        const prior = await ctx.db.query.ruleFirings.findFirst({ where: and(eq(schema.ruleFirings.ruleId, r.id), eq(schema.ruleFirings.authorExternalId, author), e.objectId ? eq(schema.ruleFirings.socialObjectId, e.objectId) : isNull(schema.ruleFirings.socialObjectId)) });
        if (prior) continue;
      }
      if (r.rateLimit.oncePerUserPerDay) {
        const prior = await ctx.db.query.ruleFirings.findFirst({ where: and(eq(schema.ruleFirings.ruleId, r.id), eq(schema.ruleFirings.authorExternalId, author), gte(schema.ruleFirings.createdAt, new Date(Date.now() - 86400000))) });
        if (prior) continue;
      }
    }
    const results: RuleOutcome["actions"] = [];
    let hiddenHere = false; // a rule may hide and then reply (e.g. phone captured → hide for privacy → thank publicly)
    for (const a of r.actions) {
      if (hidden && ["public_reply", "private_reply", "ai_reply", "like"].includes(a.type)) { results.push({ type: a.type, ok: false, detail: "skipped — comment hidden by moderation" }); continue; }
      if (opts.test) { if (a.type === "hide" || a.type === "mark_spam") hiddenHere = true; results.push({ type: a.type, ok: true, detail: describeAction(a) }); continue; }
      try {
        const detail = await runAction(ctx, r, a, e);
        if ((a.type === "hide" || a.type === "mark_spam") && e.comment) hiddenHere = true;
        results.push({ type: a.type, ok: true, detail });
      } catch (err) {
        results.push({ type: a.type, ok: false, detail: (err as Error).message.slice(0, 200) });
      }
    }
    if (hiddenHere) hidden = true;
    out.push({ ruleId: r.id, ruleName: r.name, actions: results, stopped: r.stopProcessing });
    if (!opts.test) {
      await ctx.db.insert(schema.ruleFirings).values({ workspaceId: ctx.workspace.id, ruleId: r.id, conversationId: e.conversation.id, authorExternalId: e.comment?.authorExternalId ?? e.contactId, socialObjectId: e.objectId, actions: results });
      const okOf = (t: string[]) => results.filter((x) => x.ok && t.includes(x.type)).length;
      await ctx.db.update(schema.engagementRules).set({ stats: { ...r.stats, fires: (r.stats.fires ?? 0) + 1, replies: (r.stats.replies ?? 0) + okOf(["public_reply", "private_reply", "ai_reply", "send_whatsapp_template"]), leads: (r.stats.leads ?? 0) + okOf(["create_lead"]), hides: (r.stats.hides ?? 0) + okOf(["hide", "mark_spam"]), lastFiredAt: new Date().toISOString(), rotation: r.stats.rotation ?? 0 } }).where(eq(schema.engagementRules.id, r.id));
      await emit(ctx.db, ctx.workspace.id, "engagement_rule.fired", { rule_id: r.id, rule: r.name, conversation_id: e.conversation.id, actions: results });
    }
    if (r.stopProcessing) break;
  }
  return out;
}

function describeAction(a: RuleAction) {
  const c = a.config ?? {};
  switch (a.type) {
    case "public_reply": case "private_reply": return Array.isArray(c.texts) ? `${a.type.replace("_", " ")}: “${String((c.texts as string[])[0] ?? "").slice(0, 60)}”${(c.texts as string[]).length > 1 ? ` (+${(c.texts as string[]).length - 1} variations)` : ""}` : a.type.replace("_", " ");
    case "tag": return `tag ${(c.tags as string[] | undefined)?.join(", ")}`;
    case "assign": return `assign → ${c.team ? `team ${c.team}` : "selected agents"}`;
    case "notify": return `notify ${c.roles ?? "managers"}`;
    default: return a.type.replace(/_/g, " ");
  }
}

/** SOC-053: rotate between reply variations. */
async function nextVariation(ctx: Ctx, rule: typeof schema.engagementRules.$inferSelect, texts: string[]) {
  const fresh = await ctx.db.query.engagementRules.findFirst({ where: eq(schema.engagementRules.id, rule.id) });
  const i = (fresh?.stats.rotation ?? 0) % texts.length;
  await ctx.db.update(schema.engagementRules).set({ stats: { ...(fresh?.stats ?? {}), rotation: (fresh?.stats.rotation ?? 0) + 1 } }).where(eq(schema.engagementRules.id, rule.id));
  return texts[i]!;
}

async function runAction(ctx: Ctx, rule: typeof schema.engagementRules.$inferSelect, a: RuleAction, e: RuleEvent): Promise<string> {
  const c = (a.config ?? {}) as Record<string, any>;
  const by: By = { type: "rule", ruleId: rule.id, name: `Rule: ${rule.name}` };
  const textFrom = async () => {
    if (c.savedReplyId) { const s = await ctx.db.query.cannedReplies.findFirst({ where: eq(schema.cannedReplies.id, c.savedReplyId) }); if (s) return s.body; }
    const texts: string[] = Array.isArray(c.texts) ? c.texts.filter(Boolean) : c.text ? [c.text] : [];
    if (!texts.length) throw new Error("No reply text configured");
    return nextVariation(ctx, rule, texts);
  };
  switch (a.type) {
    case "public_reply": {
      if (!e.comment) {
        if (e.trigger === "new_dm") { // in DMs a "reply" is a message (away replies — SOC-055)
          const { sendMessage } = await import("./messaging");
          const r = await sendMessage({ ...ctx, actor: actorOf(ctx, by) }, { contactId: e.contactId, channel: e.conversation.channel, body: await textFrom(), conversationId: e.conversation.id, source: "journey" });
          if (r.message?.status === "sent") await markResponded(ctx, e.conversation, by);
          return `message ${r.message?.status ?? r.blocked ?? "deferred"}`;
        }
        if (e.review) { await replyToReview(ctx, e.review.id, await textFrom(), by); return "review reply"; }
        throw new Error("Nothing to reply to");
      }
      const r = await replyToComment(ctx, e.comment.id, await textFrom(), by);
      return `replied (${r.id.slice(0, 8)})`;
    }
    case "private_reply": {
      if (!e.comment) throw new Error("Private replies need a comment");
      await privateReply(ctx, e.comment.id, await textFrom(), by);
      return "private reply sent";
    }
    case "hide": case "mark_spam": {
      if (!e.comment) throw new Error("Only comments can be hidden");
      await moderateComment(ctx, e.comment.id, a.type, by, c.reason ?? `Rule: ${rule.name}`);
      return a.type === "hide" ? "hidden" : "marked spam";
    }
    case "like": { if (!e.comment) throw new Error("Only comments can be liked"); await moderateComment(ctx, e.comment.id, "like", by); return "liked"; }
    case "tag": {
      const tags: string[] = c.tags ?? [];
      const conv = (await ctx.db.query.conversations.findFirst({ where: eq(schema.conversations.id, e.conversation.id) }))!;
      await ctx.db.update(schema.conversations).set({ tags: [...new Set([...(conv.tags ?? []), ...tags])] }).where(eq(schema.conversations.id, conv.id));
      if (c.tagContact) { const { addTags } = await import("./contacts"); await addTags(ctx, e.contactId, tags); }
      return `tagged ${tags.join(", ")}`;
    }
    case "assign": {
      const user = await pickAgent(ctx, { team: c.team ?? null, userIds: c.userIds ?? [] });
      if (!user) throw new Error("No available agent");
      await assignConversation(ctx, e.conversation.id, user, by);
      return `assigned`;
    }
    case "set_priority": {
      const p = c.priority ?? "high";
      await ctx.db.update(schema.conversations).set({ priority: p, ...(e.conversation.slaDueAt ? { slaDueAt: slaDue(ctx, e.conversation.kind, p, e.conversation.lastInboundAt ?? new Date()) } : {}) }).where(eq(schema.conversations.id, e.conversation.id));
      return `priority ${p}`;
    }
    case "create_lead": { await createLeadFromConversation(ctx, e.conversation.id, by, e.comment?.id); return "lead created"; }
    case "start_journey": {
      if (!c.journeyId) throw new Error("No journey selected");
      const { enroll } = await import("./journeys");
      await enroll(ctx, c.journeyId, e.contactId, { via: "engagement_rule", rule: rule.name });
      return "journey started";
    }
    case "notify": {
      const title = renderTemplate(String(c.title ?? `${rule.name}: new ${e.trigger.replace("new_", "")}`), { text: e.text.slice(0, 80) });
      if (c.userIds?.length) for (const u of c.userIds) await notifyUser(ctx, u, "alert", title, e.text.slice(0, 160), `/inbox?c=${e.conversation.id}`);
      else await notifyAdmins(ctx, "alert", title, e.text.slice(0, 160), `/inbox?c=${e.conversation.id}`, c.roles ?? ["workspace_admin", "marketing_manager"]);
      return "notified";
    }
    case "send_whatsapp_template": {
      const contact = (await ctx.db.query.contacts.findFirst({ where: eq(schema.contacts.id, e.contactId) }))!;
      if (!contact.phones[0]) throw new Error("No phone number for this contact");
      const { sendMessage } = await import("./messaging");
      const r = await sendMessage({ ...ctx, actor: actorOf(ctx, by) }, { contactId: contact.id, channel: "whatsapp", templateId: c.templateId, source: "journey" });
      return `whatsapp ${r.message?.status ?? r.blocked ?? "deferred"}`;
    }
    case "ai_reply": {
      const { autopilotReply } = await import("@/lib/ai/social");
      return autopilotReply(ctx, e, by);
    }
    case "block_author": {
      if (!e.comment?.authorExternalId || !e.account) throw new Error("Unknown author");
      await ctx.db.insert(schema.socialBlocklist).values({ workspaceId: ctx.workspace.id, platform: e.account.platform, authorExternalId: e.comment.authorExternalId, authorName: e.comment.authorName, reason: `Rule: ${rule.name}` }).onConflictDoNothing();
      return "author blocked";
    }
  }
  throw new Error(`Unknown action ${(a as RuleAction).type}`);
}

/** SOC-056: simulate a sample item against the rules — nothing is sent. */
export async function testRules(ctx: Ctx, sample: { text: string; channel?: string; trigger?: RuleEvent["trigger"]; accountId?: string; objectId?: string; rating?: number; newContact?: boolean; at?: string }, ruleIds?: string[]) {
  const cls = classify(sample.text, { defaultCountry: ctx.workspace.settings?.defaultCountryCode, extraProfanity: settings(ctx).moderation?.blockedWords });
  const account = sample.accountId ? await getAccount(ctx, sample.accountId) : null;
  const fake = { id: "00000000-0000-0000-0000-000000000000", channel: sample.channel ?? (account ? CHANNEL_FOR[account.platform as Platform] : "facebook_comment"), kind: sample.trigger === "new_review" ? "review" : sample.trigger === "new_dm" ? "dm" : "comment_thread" } as Conversation;
  const anyContact = await ctx.db.query.contacts.findFirst({ where: eq(schema.contacts.workspaceId, ctx.workspace.id) });
  const outcomes = await evaluateRules(ctx, { trigger: sample.trigger ?? "new_comment", conversation: fake, contactId: anyContact?.id ?? fake.id, account, objectId: sample.objectId ?? null, text: sample.text, cls, rating: sample.rating, isNewContact: !!sample.newContact, at: sample.at ? new Date(sample.at) : undefined }, { test: true, ruleIds });
  return { classification: cls, matched: outcomes };
}

/* ------------------------------------------------------------------ */
/* Periodic: SLA, snooze, escalation (SOC-028, 071, 072)                */
/* ------------------------------------------------------------------ */

export async function socialMinute(ctx: Ctx) {
  const now = new Date();
  // snooze wake-ups
  await ctx.db.update(schema.conversations).set({ status: "open", snoozedUntil: null }).where(and(eq(schema.conversations.workspaceId, ctx.workspace.id), eq(schema.conversations.status, "snoozed"), lte(schema.conversations.snoozedUntil, now)));
  // SLA breaches
  const breached = await ctx.db.select().from(schema.conversations).where(and(eq(schema.conversations.workspaceId, ctx.workspace.id), lte(schema.conversations.slaDueAt, now), isNull(schema.conversations.slaBreachedAt), isNull(schema.conversations.firstResponseAt), inArray(schema.conversations.status, ["open", "pending"]))).limit(200);
  for (const c of breached) {
    await ctx.db.update(schema.conversations).set({ slaBreachedAt: now, priority: c.priority === "urgent" ? "urgent" : "high" }).where(eq(schema.conversations.id, c.id));
    await emit(ctx.db, ctx.workspace.id, "conversation.sla_breached", { conversation_id: c.id, channel: c.channel, kind: c.kind, due_at: c.slaDueAt });
    if (settings(ctx).escalation === "reassign") {
      const next = await pickAgent(ctx, {});
      if (next && next !== c.assigneeId) await assignConversation(ctx, c.id, next, { type: "rule", name: "SLA escalation" });
    }
    await notifyAdmins(ctx, "sla", `SLA breached: ${c.kind === "comment_thread" ? "comment" : c.kind} on ${c.channel.replace("_", " ")}`, "No response within the target time", `/inbox?c=${c.id}`, ["workspace_admin", "marketing_manager"]);
  }
  // release stale locks
  await ctx.db.update(schema.conversations).set({ lockedByUserId: null, lockedUntil: null }).where(and(eq(schema.conversations.workspaceId, ctx.workspace.id), lte(schema.conversations.lockedUntil, now)));
  return breached.length;
}

/* ------------------------------------------------------------------ */
/* Analytics (SOC-080…084)                                              */
/* ------------------------------------------------------------------ */

const pctl = (arr: number[], p: number) => { if (!arr.length) return null; const s = [...arr].sort((a, b) => a - b); return s[Math.min(s.length - 1, Math.ceil((s.length - 1) * p))]!; };
export const median = (arr: number[]) => { if (!arr.length) return null; const s = [...arr].sort((a, b) => a - b); const m = Math.floor(s.length / 2); return s.length % 2 ? s[m]! : (s[m - 1]! + s[m]!) / 2; };

export async function engagementReport(ctx: Ctx, from: Date, to: Date, groupBy: "channel" | "account" | "agent" | "day" = "channel") {
  const ws = ctx.workspace.id;
  const allowed = await allowedAccountIds(ctx);
  const convs = await ctx.db.select().from(schema.conversations).where(and(eq(schema.conversations.workspaceId, ws), gte(schema.conversations.createdAt, from), lte(schema.conversations.createdAt, to), allowed ? or(isNull(schema.conversations.socialAccountId), inArray(schema.conversations.socialAccountId, allowed)) : undefined));
  const accounts = new Map((await ctx.db.select().from(schema.socialAccounts).where(eq(schema.socialAccounts.workspaceId, ws))).map((a) => [a.id, a.name]));
  const users = new Map((await ctx.db.select({ id: schema.users.id, name: schema.users.name }).from(schema.users)).map((u) => [u.id, u.name]));
  const convIds = convs.map((c) => c.id);
  const inboundComments = convIds.length ? await ctx.db.select({ c: schema.comments.conversationId, n: sql<number>`count(*)::int`, hidden: sql<number>`count(*) FILTER (WHERE is_hidden)::int`, neg: sql<number>`count(*) FILTER (WHERE sentiment = 'negative')::int` }).from(schema.comments).where(and(inArray(schema.comments.conversationId, convIds), eq(schema.comments.direction, "inbound"))).groupBy(schema.comments.conversationId) : [];
  const inboundMsgs = convIds.length ? await ctx.db.select({ c: schema.messages.conversationId, n: sql<number>`count(*) FILTER (WHERE direction = 'in')::int`, human: sql<number>`count(*) FILTER (WHERE direction = 'out' AND sender_id IS NOT NULL)::int`, firstIn: sql<string | null>`min(created_at) FILTER (WHERE direction = 'in')`, firstOut: sql<string | null>`min(created_at) FILTER (WHERE direction = 'out' AND broadcast_id IS NULL)` }).from(schema.messages).where(and(inArray(schema.messages.conversationId, convIds))).groupBy(schema.messages.conversationId) : [];
  const humanComment = convIds.length ? await ctx.db.select({ c: schema.comments.conversationId, n: sql<number>`count(*)::int` }).from(schema.comments).where(and(inArray(schema.comments.conversationId, convIds), eq(schema.comments.direction, "outbound"), sql`sent_by_user_id IS NOT NULL`)).groupBy(schema.comments.conversationId) : [];
  const ic = new Map(inboundComments.map((r) => [r.c, r])), im = new Map(inboundMsgs.map((r) => [r.c, r])), hc = new Map(humanComment.map((r) => [r.c, r.n]));
  const leads = await ctx.db.select({ contactId: schema.events.contactId, props: schema.events.properties, at: schema.events.occurredAt }).from(schema.events).where(and(eq(schema.events.workspaceId, ws), eq(schema.events.name, "social.lead_created"), gte(schema.events.occurredAt, from), lte(schema.events.occurredAt, to)));
  const leadConv = new Set(leads.map((l) => String((l.props as Record<string, unknown>).conversation_id)));
  const keyOf = (c: typeof convs[number]) => groupBy === "channel" ? c.channel : groupBy === "account" ? (accounts.get(c.socialAccountId ?? "") ?? "(direct DMs)") : groupBy === "agent" ? (users.get(c.assigneeId ?? "") ?? "(unassigned)") : c.createdAt.toISOString().slice(0, 10);
  type G = { key: string; inbound: number; conversations: number; replied: number; resolved: number; hidden: number; negative: number; leads: number; automated: number; frt: number[]; res: number[] };
  const groups = new Map<string, G>();
  const total: G = { key: "Total", inbound: 0, conversations: 0, replied: 0, resolved: 0, hidden: 0, negative: 0, leads: 0, automated: 0, frt: [], res: [] };
  for (const c of convs) {
    const k = keyOf(c);
    const g = groups.get(k) ?? (groups.set(k, { key: k, inbound: 0, conversations: 0, replied: 0, resolved: 0, hidden: 0, negative: 0, leads: 0, automated: 0, frt: [], res: [] }), groups.get(k)!);
    const inbound = (ic.get(c.id)?.n ?? 0) + (c.kind === "review" ? 1 : 0) + (c.kind === "dm" ? im.get(c.id)?.n ?? 0 : 0);
    // DMs from before Module 11 have no first_response_at: derive it from the first human reply after the first inbound message
    const m = im.get(c.id);
    const derived = !c.firstResponseAt && c.kind === "dm" && m?.firstIn && m.firstOut && new Date(m.firstOut) > new Date(m.firstIn) ? { at: new Date(m.firstOut), from: new Date(m.firstIn) } : null;
    const respondedAt = c.firstResponseAt ?? derived?.at ?? null;
    // response cycles restart on a new inbound after a reply, so measure from the latest inbound that preceded the response
    const start = derived?.from ?? (c.lastInboundAt && c.firstResponseAt && c.lastInboundAt <= c.firstResponseAt ? c.lastInboundAt : c.createdAt);
    const frt = respondedAt ? Math.max(0, (respondedAt.getTime() - start.getTime()) / 1000) : null;
    const res = c.resolvedAt ? (c.resolvedAt.getTime() - c.createdAt.getTime()) / 1000 : null;
    const automated = respondedAt && (c.handledBy === "rule" || c.handledBy === "ai") && !(hc.get(c.id)) && !(im.get(c.id)?.human);
    for (const t of [g, total]) {
      t.conversations++; t.inbound += inbound; if (respondedAt) t.replied++; if (c.resolvedAt) t.resolved++;
      t.hidden += ic.get(c.id)?.hidden ?? 0; t.negative += (ic.get(c.id)?.neg ?? 0) + (c.kind !== "comment_thread" && c.sentiment === "negative" ? 1 : 0);
      if (leadConv.has(c.id)) t.leads++; if (automated) t.automated++;
      if (frt !== null && frt >= 0) t.frt.push(frt); if (res !== null && res >= 0) t.res.push(res);
    }
  }
  const shape = (g: G) => ({ key: g.key, conversations: g.conversations, inbound: g.inbound, replied: g.replied, repliedPct: g.conversations ? (g.replied / g.conversations) * 100 : 0, resolved: g.resolved, hidden: g.hidden, negative: g.negative, leads: g.leads, automatedPct: g.replied ? (g.automated / g.replied) * 100 : 0, medianFirstResponseS: median(g.frt), p90FirstResponseS: pctl(g.frt, 0.9), medianResolutionS: median(g.res) });
  // sentiment/intent over time + top objects (SOC-081) and leads/won by object (SOC-082)
  const daily = new Map<string, { date: string; positive: number; neutral: number; negative: number }>();
  const intents = new Map<string, number>();
  const cm = convIds.length ? await ctx.db.select({ s: schema.comments.sentiment, i: schema.comments.intent, d: schema.comments.externalCreatedAt, o: schema.comments.socialObjectId }).from(schema.comments).where(and(inArray(schema.comments.conversationId, convIds), eq(schema.comments.direction, "inbound"))) : [];
  const objStats = new Map<string, { total: number; negative: number }>();
  for (const r of cm) {
    const d = r.d.toISOString().slice(0, 10);
    const row = daily.get(d) ?? (daily.set(d, { date: d, positive: 0, neutral: 0, negative: 0 }), daily.get(d)!);
    row[(r.s as "positive" | "neutral" | "negative") ?? "neutral"]++;
    if (r.i) intents.set(r.i, (intents.get(r.i) ?? 0) + 1);
    if (r.o) { const s = objStats.get(r.o) ?? { total: 0, negative: 0 }; s.total++; if (r.s === "negative") s.negative++; objStats.set(r.o, s); }
  }
  const objIds = [...objStats.keys()];
  const objs = objIds.length ? await ctx.db.select().from(schema.socialObjects).where(inArray(schema.socialObjects.id, objIds)) : [];
  const leadByObj = new Map<string, number>();
  for (const l of leads) { const o = String((l.props as Record<string, unknown>).object_id ?? ""); if (o) leadByObj.set(o, (leadByObj.get(o) ?? 0) + 1); }
  const leadContacts = [...new Set(leads.map((l) => l.contactId).filter(Boolean) as string[])];
  const wonDeals = leadContacts.length ? await ctx.db.select({ contactId: schema.deals.contactId, value: schema.deals.value }).from(schema.deals).where(and(inArray(schema.deals.contactId, leadContacts), sql`${schema.deals.wonAt} IS NOT NULL`)) : [];
  const contactObj = new Map(leads.map((l) => [l.contactId, String((l.props as Record<string, unknown>).object_id ?? "")]));
  const wonByObj = new Map<string, { won: number; revenue: number }>();
  for (const d of wonDeals) { const o = contactObj.get(d.contactId) ?? ""; const s = wonByObj.get(o) ?? { won: 0, revenue: 0 }; s.won++; s.revenue += Number(d.value); wonByObj.set(o, s); }
  const topObjects = objs.map((o) => ({ id: o.id, type: o.type, caption: o.captionExcerpt, permalink: o.permalink, thumbnail: o.thumbnailUrl, campaign: o.campaignName, adId: o.externalAdId, account: accounts.get(o.socialAccountId), comments: objStats.get(o.id)?.total ?? 0, negativeShare: objStats.get(o.id)?.total ? ((objStats.get(o.id)!.negative / objStats.get(o.id)!.total) * 100) : 0, leads: leadByObj.get(o.id) ?? 0, won: wonByObj.get(o.id)?.won ?? 0, revenue: wonByObj.get(o.id)?.revenue ?? 0 })).sort((a, b) => b.comments - a.comments);
  const rules = await ctx.db.select().from(schema.engagementRules).where(eq(schema.engagementRules.workspaceId, ws));
  const firings = await ctx.db.select({ r: schema.ruleFirings.ruleId, n: sql<number>`count(*)::int` }).from(schema.ruleFirings).where(and(eq(schema.ruleFirings.workspaceId, ws), gte(schema.ruleFirings.createdAt, from), lte(schema.ruleFirings.createdAt, to))).groupBy(schema.ruleFirings.ruleId);
  return {
    total: shape(total), groups: [...groups.values()].map(shape).sort((a, b) => b.conversations - a.conversations),
    sentimentDaily: [...daily.values()].sort((a, b) => a.date.localeCompare(b.date)), intents: [...intents].map(([intent, count]) => ({ intent, count })).sort((a, b) => b.count - a.count),
    topObjects, rules: rules.map((r) => ({ id: r.id, name: r.name, type: r.type, fires: firings.find((f) => f.r === r.id)?.n ?? 0, totalFires: r.stats.fires ?? 0, replies: r.stats.replies ?? 0, leads: r.stats.leads ?? 0, hides: r.stats.hides ?? 0 })),
  };
}

/** Daily rollup into engagement_metrics_daily (SOC-080 storage). */
export async function rollupMetrics(ctx: Ctx, day = new Date(Date.now() - 86400000)) {
  const d = day.toISOString().slice(0, 10);
  const from = new Date(`${d}T00:00:00Z`), to = new Date(`${d}T23:59:59Z`);
  const r = await engagementReport(ctx, from, to, "channel");
  await ctx.db.delete(schema.engagementMetricsDaily).where(and(eq(schema.engagementMetricsDaily.workspaceId, ctx.workspace.id), eq(schema.engagementMetricsDaily.date, d)));
  for (const g of r.groups) await ctx.db.insert(schema.engagementMetricsDaily).values({ workspaceId: ctx.workspace.id, date: d, channel: g.key, inboundCount: g.inbound, repliedCount: g.replied, medianFirstResponseS: g.medianFirstResponseS == null ? null : Math.round(g.medianFirstResponseS), p90FirstResponseS: g.p90FirstResponseS == null ? null : Math.round(g.p90FirstResponseS), resolvedCount: g.resolved, hiddenCount: g.hidden, negativeCount: g.negative, leadsCreated: g.leads });
  return r.groups.length;
}

export { asc, LEAD_INTENTS, CAPABILITIES };
