/** Module 11 — social inbox & engagement API (spec §8). Every outbound platform action goes through the connector layer. */
import { z } from "zod";
import { and, desc, eq, gte, ilike, inArray, isNull, lte, or, sql, type SQL } from "drizzle-orm";
import { schema } from "@/db";
import { route } from "../router";
import { ApiError, body, filterParams, forbidden, notFound } from "@/lib/api";
import { audit } from "@/lib/audit";
import { can } from "@/lib/rbac";
import { extractVariables } from "@/lib/util";
import type { Ctx } from "@/lib/auth";
import * as social from "@/lib/services/social";
import * as accounts from "@/lib/services/social-accounts";
import { CAPABILITIES } from "@/connectors/social";

const user = (ctx: Ctx) => ({ type: "user" as const, userId: ctx.user?.id ?? null, name: ctx.actor.name });
const needRules = (ctx: Ctx) => social.assertSocial(ctx, "rules");
const needAdminOrRules = (ctx: Ctx) => { if (!can(ctx.perms, "admin", "edit") && !can(ctx.perms, "social_rules", "edit")) throw forbidden("Admin or social.rules.manage permission required"); };

/* ---------------- accounts (SOC-001…007) ---------------- */

route({ method: "GET", path: "/social/accounts", tag: "Social", scope: "social:read", summary: "Connected social accounts with status, capabilities, webhook and backfill health", handler: async (_r, ctx) => {
  const rows = await ctx.db.select().from(schema.socialAccounts).where(eq(schema.socialAccounts.workspaceId, ctx.workspace.id)).orderBy(schema.socialAccounts.platform, schema.socialAccounts.name);
  const counts = await ctx.db.select({ a: schema.conversations.socialAccountId, open: sql<number>`count(*) FILTER (WHERE status IN ('open','pending'))::int`, total: sql<number>`count(*)::int` }).from(schema.conversations).where(and(eq(schema.conversations.workspaceId, ctx.workspace.id), sql`${schema.conversations.socialAccountId} IS NOT NULL`)).groupBy(schema.conversations.socialAccountId);
  const ints = new Map((await ctx.db.select({ id: schema.integrations.id, provider: schema.integrations.provider, mode: schema.integrations.mode, status: schema.integrations.status }).from(schema.integrations).where(eq(schema.integrations.workspaceId, ctx.workspace.id))).map((i) => [i.id, i]));
  return { data: rows.map((a) => ({ ...a, integration: a.integrationId ? ints.get(a.integrationId) ?? null : null, open: counts.find((c) => c.a === a.id)?.open ?? 0, total: counts.find((c) => c.a === a.id)?.total ?? 0, polled: accounts.POLLED_PLATFORMS.includes(a.platform) })) };
} });
route({ method: "POST", path: "/social/accounts/discover", tag: "Social", scope: "admin", summary: "Discover pages / IG accounts / channels / locations from connected integrations (new ones start inactive)", body: z.object({ integration_id: z.string().uuid().optional() }), handler: async (req, ctx) => {
  needAdminOrRules(ctx);
  const b = await body(req, z.object({ integration_id: z.string().uuid().optional() }));
  return { data: await accounts.discover(ctx, b.integration_id) };
} });
route({ method: "POST", path: "/social/accounts/:id/activate", tag: "Social", scope: "admin", summary: "Activate an account: subscribe webhooks and start a 30-day backfill", handler: async (_r, ctx, p) => {
  needAdminOrRules(ctx);
  const a = await social.getAccount(ctx, p.id!);
  const flags = ctx.workspace.settings?.social?.featureFlags ?? {};
  if ((a.platform === "tiktok" && !flags.tiktok) || (a.platform === "linkedin" && !flags.linkedin)) throw new ApiError(409, "feature_disabled", `${a.platform === "tiktok" ? "TikTok" : "LinkedIn"} comments are behind a feature flag — enable it in Settings → Social first`);
  return { data: await accounts.setActive(ctx, p.id!, true) };
} });
route({ method: "POST", path: "/social/accounts/:id/deactivate", tag: "Social", scope: "admin", summary: "Deactivate an account (stops ingest; history is kept)", handler: async (_r, ctx, p) => {
  needAdminOrRules(ctx);
  return { data: await accounts.setActive(ctx, p.id!, false) };
} });
route({ method: "POST", path: "/social/accounts/:id/backfill", tag: "Social", scope: "admin", summary: "Re-run the 30-day backfill (no auto-replies on historical items)", handler: async (_r, ctx, p) => {
  needAdminOrRules(ctx);
  return { data: await accounts.runBackfill(ctx, p.id!) };
} });
route({ method: "POST", path: "/social/accounts/:id/poll", tag: "Social", scope: "social:write", summary: "Poll now (YouTube, Google reviews, TikTok, LinkedIn; safety net for Meta)", handler: async (_r, ctx, p) => {
  social.assertSocial(ctx, "reply");
  return { data: await accounts.pollAccount(ctx, p.id!) };
} });
const simIn = z.object({ kind: z.enum(["comment", "review", "dm"]).default("comment"), text: z.string().min(1).max(4000), author_name: z.string().max(120).optional(), author_id: z.string().max(120).optional(), rating: z.number().int().min(1).max(5).optional(), object_external_id: z.string().max(200).optional(), object_caption: z.string().max(500).optional(), external_ad_id: z.string().max(100).optional(), parent_comment_id: z.string().max(200).optional() });
route({ method: "POST", path: "/social/accounts/:id/simulate", tag: "Social", scope: "social:write", summary: "Inject a test comment, review or DM on a sandbox account (runs the full pipeline: identity → moderation → rules → routing)", body: simIn, handler: async (req, ctx, p) => {
  social.assertSocial(ctx, "reply");
  const b = await body(req, simIn);
  return { data: await accounts.simulateInbound(ctx, p.id!, { kind: b.kind, text: b.text, authorName: b.author_name, authorId: b.author_id, rating: b.rating, objectExternalId: b.object_external_id, objectCaption: b.object_caption, externalAdId: b.external_ad_id, parentCommentId: b.parent_comment_id }) };
} });
route({ method: "GET", path: "/social/capabilities", tag: "Social", summary: "Per-platform capability matrix", handler: async () => ({ data: CAPABILITIES }) });

/* ---------------- posts / ads (SOC-014/015) ---------------- */

route({ method: "GET", path: "/social/objects", tag: "Social", scope: "social:read", summary: "Posts, reels, videos and ads that received comments (?filter[account]=&filter[type]=ad&q=)", handler: async (req, ctx) => {
  const f = filterParams(req);
  const q = req.nextUrl.searchParams.get("q");
  const O = schema.socialObjects;
  const conds: (SQL | undefined)[] = [eq(O.workspaceId, ctx.workspace.id)];
  if (f.account) conds.push(eq(O.socialAccountId, f.account));
  if (f.type) conds.push(eq(O.type, f.type));
  if (q) conds.push(or(ilike(O.captionExcerpt, `%${q}%`), ilike(O.campaignName, `%${q}%`)));
  const rows = await ctx.db.select({ o: O, comments: sql<number>`(SELECT count(*)::int FROM comments c WHERE c.social_object_id = ${O.id} AND c.direction = 'inbound')`, open: sql<number>`(SELECT count(*)::int FROM conversations v WHERE v.social_object_id = ${O.id} AND v.status IN ('open','pending'))` }).from(O).where(and(...conds)).orderBy(desc(O.createdAt)).limit(200);
  return { data: rows.map((r) => ({ ...r.o, comments: r.comments, open: r.open })) };
} });

/* ---------------- conversation operations (SOC-020…028) ---------------- */

route({ method: "POST", path: "/conversations/:id/assign", tag: "Social", scope: "write:messages", summary: "Assign to a user (or null to unassign); auto = round-robin within a team", body: z.object({ user_id: z.string().uuid().nullable().optional(), team: z.string().optional(), auto: z.boolean().optional() }), handler: async (req, ctx, p) => {
  const b = await body(req, z.object({ user_id: z.string().uuid().nullable().optional(), team: z.string().optional(), auto: z.boolean().optional() }));
  const conv = await ctx.db.query.conversations.findFirst({ where: and(eq(schema.conversations.id, p.id!), eq(schema.conversations.workspaceId, ctx.workspace.id)) });
  if (!conv) throw notFound("Conversation");
  const level = conv.kind === "dm" ? ctx.perms.messaging : ctx.perms.social;
  if (level !== "C") throw forbidden("Your role can't reassign conversations");
  const target = b.auto || b.team ? await social.pickAgent(ctx, { team: b.team ?? null }) : b.user_id ?? null;
  if ((b.auto || b.team) && !target) throw new ApiError(409, "no_agent", "No available agent (everyone is away)");
  return { data: await social.assignConversation(ctx, conv.id, target, user(ctx)) };
} });
route({ method: "POST", path: "/conversations/:id/status", tag: "Social", scope: "write:messages", summary: "Set status open | pending | snoozed | resolved | closed (snoozed requires until)", body: z.object({ status: z.enum(["open", "pending", "snoozed", "resolved", "closed"]), until: z.string().datetime().optional() }), handler: async (req, ctx, p) => {
  const b = await body(req, z.object({ status: z.enum(["open", "pending", "snoozed", "resolved", "closed"]), until: z.string().datetime().optional() }));
  return { data: await social.setStatus(ctx, p.id!, b.status, b.until ? new Date(b.until) : undefined) };
} });
route({ method: "POST", path: "/conversations/:id/snooze", tag: "Social", scope: "write:messages", summary: "Snooze until a time; reopens automatically or on a new inbound", body: z.object({ until: z.string().datetime() }), handler: async (req, ctx, p) => {
  const b = await body(req, z.object({ until: z.string().datetime() }));
  if (new Date(b.until) <= new Date()) throw new ApiError(422, "validation_failed", "Snooze time must be in the future");
  return { data: await social.setStatus(ctx, p.id!, "snoozed", new Date(b.until)) };
} });
route({ method: "PUT", path: "/conversations/:id/tags", tag: "Social", scope: "write:messages", summary: "Replace conversation tags", body: z.object({ tags: z.array(z.string().max(40)).max(30) }), handler: async (req, ctx, p) => {
  const b = await body(req, z.object({ tags: z.array(z.string().max(40)).max(30) }));
  return { data: await social.setTags(ctx, p.id!, b.tags) };
} });
route({ method: "POST", path: "/conversations/:id/notes", tag: "Social", scope: "write:messages", summary: "Internal note; @FirstName mentions notify teammates", body: z.object({ body: z.string().min(1).max(4000) }), handler: async (req, ctx, p) => {
  const b = await body(req, z.object({ body: z.string().min(1).max(4000) }));
  return { data: await social.addNote(ctx, p.id!, b.body) };
} });
route({ method: "POST", path: "/conversations/:id/lock", tag: "Social", scope: "write:messages", summary: "Soft-lock while replying (2 minutes); force=true overrides; release=true unlocks", body: z.object({ release: z.boolean().optional(), force: z.boolean().optional() }), handler: async (req, ctx, p) => {
  const b = await body(req, z.object({ release: z.boolean().optional(), force: z.boolean().optional() }));
  return { data: await social.lockConversation(ctx, p.id!, b.release, b.force) };
} });
route({ method: "POST", path: "/conversations/:id/create-lead", tag: "Social", scope: "write:leads", summary: "Create a lead/deal from a social conversation (attributed to the post/ad and campaign)", body: z.object({ comment_id: z.string().uuid().optional() }), handler: async (req, ctx, p) => {
  const b = await body(req, z.object({ comment_id: z.string().uuid().optional() }));
  return { data: await social.createLeadFromConversation(ctx, p.id!, user(ctx), b.comment_id) };
} });
route({ method: "POST", path: "/conversations/:id/move-to-whatsapp", tag: "Social", scope: "social:write", summary: "Continue on WhatsApp: approved template when opted in, else a click-to-chat link via private reply / DM", handler: async (_r, ctx, p) => ({ data: await social.moveToWhatsApp(ctx, p.id!, user(ctx)) }) });
route({ method: "POST", path: "/conversations/:id/handoff", tag: "Social", scope: "write:messages", summary: "Stop the AI agent and hand the conversation to a human", body: z.object({ reason: z.string().max(300).optional() }), handler: async (req, ctx, p) => {
  const b = await body(req, z.object({ reason: z.string().max(300).optional() }));
  await social.handoffToHuman(ctx, p.id!, b.reason ?? `Taken over by ${ctx.actor.name}`);
  return { ok: true };
} });
const bulkIn = z.object({ ids: z.array(z.string().uuid()).min(1).max(200), action: z.enum(["assign", "resolve", "close", "open", "snooze", "tag", "hide", "mark_spam"]), user_id: z.string().uuid().nullable().optional(), until: z.string().datetime().optional(), tags: z.array(z.string()).optional() });
route({ method: "POST", path: "/conversations/bulk", tag: "Social", scope: "write:messages", summary: "Bulk assign / resolve / snooze / tag / hide / mark spam (SOC-027)", body: bulkIn, handler: async (req, ctx) => {
  const b = await body(req, bulkIn);
  const results: { id: string; ok: boolean; error?: string }[] = [];
  for (const id of b.ids) {
    try {
      if (b.action === "assign") await social.assignConversation(ctx, id, b.user_id ?? null, user(ctx));
      else if (b.action === "resolve" || b.action === "close" || b.action === "open") await social.setStatus(ctx, id, b.action === "resolve" ? "resolved" : b.action === "close" ? "closed" : "open");
      else if (b.action === "snooze") await social.setStatus(ctx, id, "snoozed", b.until ? new Date(b.until) : new Date(Date.now() + 3600000));
      else if (b.action === "tag") {
        const c = await ctx.db.query.conversations.findFirst({ where: and(eq(schema.conversations.id, id), eq(schema.conversations.workspaceId, ctx.workspace.id)) });
        if (!c) throw new Error("Not found");
        await social.setTags(ctx, id, [...(c.tags ?? []), ...(b.tags ?? [])]);
      } else {
        const comments = await ctx.db.select({ id: schema.comments.id }).from(schema.comments).where(and(eq(schema.comments.conversationId, id), eq(schema.comments.direction, "inbound"), eq(schema.comments.isHidden, false)));
        if (!comments.length) throw new Error("No visible comments");
        for (const c of comments) await social.moderateComment(ctx, c.id, b.action, user(ctx), b.action === "mark_spam" ? "Bulk: spam" : "Bulk hide");
      }
      results.push({ id, ok: true });
    } catch (e) { results.push({ id, ok: false, error: (e as Error).message }); }
  }
  return { data: results, ok: results.filter((r) => r.ok).length, failed: results.filter((r) => !r.ok).length };
} });

/* ---------------- comments (SOC-030…036) ---------------- */

route({ method: "POST", path: "/comments/:id/reply", tag: "Social", scope: "social:write", summary: "Public reply to a comment (rendered with {{first_name}} etc.)", body: z.object({ body: z.string().min(1).max(8000) }), handler: async (req, ctx, p) => {
  const b = await body(req, z.object({ body: z.string().min(1).max(8000) }));
  return { data: await social.replyToComment(ctx, p.id!, b.body, user(ctx)) };
} });
route({ method: "POST", path: "/comments/:id/private-reply", tag: "Social", scope: "social:write", summary: "Private reply (Messenger / Instagram DM) to the commenter — once per comment, within the platform window", body: z.object({ body: z.string().min(1).max(2000) }), handler: async (req, ctx, p) => {
  const b = await body(req, z.object({ body: z.string().min(1).max(2000) }));
  return { data: await social.privateReply(ctx, p.id!, b.body, user(ctx)) };
} });
for (const action of ["hide", "unhide", "like", "unlike", "delete", "mark_spam"] as const) {
  const path = action === "mark_spam" ? "mark-spam" : action;
  route({ method: "POST", path: `/comments/:id/${path}`, tag: "Social", scope: action === "like" || action === "unlike" ? "social:write" : "social:moderate", summary: `${action.replace("_", " ")} a comment${action === "delete" ? " (irreversible on the platform)" : ""}`, body: z.object({ reason: z.string().max(300).optional() }), handler: async (req, ctx, p) => {
    const b = (await req.json().catch(() => ({}))) as { reason?: unknown };
    return { data: await social.moderateComment(ctx, p.id!, action, user(ctx), typeof b.reason === "string" ? b.reason.slice(0, 300) : undefined) };
  } });
}
route({ method: "POST", path: "/comments/:id/retry", tag: "Social", scope: "social:write", summary: "Retry a failed outbound reply", handler: async (_r, ctx, p) => ({ data: await social.retrySend(ctx, p.id!, user(ctx)) }) });
route({ method: "POST", path: "/comments/:id/create-lead", tag: "Social", scope: "write:leads", summary: "Create a lead from a comment (attribution: post/ad, campaign)", handler: async (_r, ctx, p) => {
  const c = await ctx.db.query.comments.findFirst({ where: and(eq(schema.comments.id, p.id!), eq(schema.comments.workspaceId, ctx.workspace.id)) });
  if (!c) throw notFound("Comment");
  return { data: await social.createLeadFromConversation(ctx, c.conversationId, user(ctx), c.id) };
} });
route({ method: "POST", path: "/comments/:id/block-author", tag: "Social", scope: "social:moderate", summary: "Block the comment author — their future comments are hidden automatically", handler: async (_r, ctx, p) => {
  social.assertSocial(ctx, "moderate");
  const c = await ctx.db.query.comments.findFirst({ where: and(eq(schema.comments.id, p.id!), eq(schema.comments.workspaceId, ctx.workspace.id)) });
  if (!c?.authorExternalId) throw notFound("Comment author");
  const conv = (await ctx.db.query.conversations.findFirst({ where: eq(schema.conversations.id, c.conversationId) }))!;
  const acct = conv.socialAccountId ? await social.getAccount(ctx, conv.socialAccountId) : null;
  if (!acct) throw new ApiError(409, "conflict", "No social account");
  await ctx.db.insert(schema.socialBlocklist).values({ workspaceId: ctx.workspace.id, platform: acct.platform, authorExternalId: c.authorExternalId, authorName: c.authorName, reason: `Blocked by ${ctx.actor.name}` }).onConflictDoNothing();
  await audit(ctx, "social.block_author", "comment", c.id, undefined, { author: c.authorExternalId });
  return { ok: true };
} });

/* ---------------- reviews (SOC-060/061) ---------------- */

route({ method: "GET", path: "/reviews", tag: "Social", scope: "social:read", summary: "Google reviews (?filter[rating_max]=2&filter[reply]=none|published|pending_approval)", handler: async (req, ctx) => {
  const f = filterParams(req);
  const R = schema.reviews;
  const rows = await ctx.db.select().from(R).where(and(eq(R.workspaceId, ctx.workspace.id), f.rating_max ? lte(R.rating, Number(f.rating_max)) : undefined, f.reply ? eq(R.replyStatus, f.reply) : undefined, f.account ? eq(R.socialAccountId, f.account) : undefined)).orderBy(desc(R.externalCreatedAt)).limit(300);
  return { data: rows };
} });
route({ method: "POST", path: "/reviews/:id/reply", tag: "Social", scope: "social:write", summary: "Publish (or edit) the owner reply to a Google review", body: z.object({ body: z.string().min(1).max(4096) }), handler: async (req, ctx, p) => {
  const b = await body(req, z.object({ body: z.string().min(1).max(4096) }));
  return { data: await social.replyToReview(ctx, p.id!, b.body, user(ctx)) };
} });

/* ---------------- engagement rules (SOC-050…058) ---------------- */

const actionIn = z.object({ type: z.enum(["public_reply", "private_reply", "hide", "like", "tag", "assign", "set_priority", "create_lead", "start_journey", "notify", "send_whatsapp_template", "ai_reply", "mark_spam", "block_author"]), config: z.record(z.unknown()).optional() });
const ruleIn = z.object({
  name: z.string().min(1).max(120), type: z.enum(["auto_reply", "comment_to_dm", "moderation", "routing", "ai_autopilot", "alert"]),
  channels: z.array(z.string()).default([]), social_account_ids: z.array(z.string().uuid()).default([]), social_object_ids: z.array(z.string().uuid()).default([]),
  trigger: z.enum(["new_comment", "new_dm", "new_review", "any"]).default("new_comment"),
  conditions: z.object({
    keywords: z.array(z.string().max(80)).max(100).optional(), keywordMode: z.enum(["any", "all"]).optional(), intents: z.array(z.string()).optional(), sentiments: z.array(z.enum(["positive", "neutral", "negative"])).optional(),
    maxRating: z.number().int().min(1).max(5).optional(), languages: z.array(z.enum(["en", "bn", "banglish"])).optional(), firstMessageFromNewContact: z.boolean().optional(), hasPhone: z.boolean().optional(), hasLink: z.boolean().optional(),
    profanity: z.boolean().optional(), competitorNames: z.array(z.string()).optional(), contactField: z.object({ field: z.string(), value: z.string() }).optional(),
  }).default({}),
  actions: z.array(actionIn).min(1).max(10), priority: z.number().int().min(0).max(10000).default(100), stop_processing: z.boolean().default(false), is_active: z.boolean().default(true),
  schedule: z.object({ mode: z.enum(["always", "in_hours", "out_of_hours"]).optional(), days: z.array(z.number().int().min(0).max(6)).optional(), start: z.string().regex(/^\d{2}:\d{2}$/).optional(), end: z.string().regex(/^\d{2}:\d{2}$/).optional(), timezone: z.string().optional() }).default({}),
  rate_limit: z.object({ perMinute: z.number().int().min(1).max(600).optional(), oncePerUserPerObject: z.boolean().optional(), oncePerUserPerDay: z.boolean().optional() }).default({}),
});
function validateRule(b: Partial<z.infer<typeof ruleIn>>) {
  for (const a of b.actions ?? []) {
    const c = (a.config ?? {}) as Record<string, unknown>;
    if ((a.type === "public_reply" || a.type === "private_reply") && !c.savedReplyId && !(Array.isArray(c.texts) && c.texts.some(Boolean)) && !c.text) throw new ApiError(422, "validation_failed", `${a.type.replace("_", " ")} needs reply text or a saved reply`);
    if (a.type === "private_reply" && b.trigger && b.trigger !== "new_comment" && b.trigger !== "any") throw new ApiError(422, "validation_failed", "Private replies only work on comments");
    if (a.type === "start_journey" && !c.journeyId) throw new ApiError(422, "validation_failed", "Choose a journey");
    if (a.type === "send_whatsapp_template" && !c.templateId) throw new ApiError(422, "validation_failed", "Choose a WhatsApp template");
  }
  // auto-replies without a rate limit can spam — default once per user per post
  if (b.actions?.some((a) => a.type === "public_reply" || a.type === "private_reply") && b.rate_limit && !b.rate_limit.oncePerUserPerObject && !b.rate_limit.oncePerUserPerDay && !b.rate_limit.perMinute) b.rate_limit.oncePerUserPerObject = true;
}
const toRow = (b: Partial<z.infer<typeof ruleIn>>) => ({
  ...(b.name !== undefined ? { name: b.name } : {}), ...(b.type ? { type: b.type } : {}), ...(b.channels ? { channels: b.channels } : {}), ...(b.social_account_ids ? { socialAccountIds: b.social_account_ids } : {}), ...(b.social_object_ids ? { socialObjectIds: b.social_object_ids } : {}),
  ...(b.trigger ? { trigger: b.trigger } : {}), ...(b.conditions ? { conditions: b.conditions } : {}), ...(b.actions ? { actions: b.actions } : {}), ...(b.priority !== undefined ? { priority: b.priority } : {}),
  ...(b.stop_processing !== undefined ? { stopProcessing: b.stop_processing } : {}), ...(b.is_active !== undefined ? { isActive: b.is_active } : {}), ...(b.schedule ? { schedule: b.schedule } : {}), ...(b.rate_limit ? { rateLimit: b.rate_limit } : {}),
});
route({ method: "GET", path: "/engagement-rules", tag: "Social", scope: "social:read", summary: "Engagement rules (auto-reply, comment-to-DM, moderation, routing, AI, alerts) in evaluation order", handler: async (_r, ctx) => ({ data: (await ctx.db.select().from(schema.engagementRules).where(eq(schema.engagementRules.workspaceId, ctx.workspace.id))).sort((a, b) => (a.type === "moderation" ? 0 : 1) - (b.type === "moderation" ? 0 : 1) || a.priority - b.priority) }) });
route({ method: "POST", path: "/engagement-rules", tag: "Social", scope: "rules:write", summary: "Create a rule", body: ruleIn, handler: async (req, ctx) => {
  needRules(ctx);
  const b = await body(req, ruleIn);
  validateRule(b);
  if (b.actions.some((a) => a.type === "ai_reply")) social.assertSocial(ctx, "ai");
  const [r] = await ctx.db.insert(schema.engagementRules).values({ workspaceId: ctx.workspace.id, createdBy: ctx.user?.id ?? null, ...toRow(b) } as typeof schema.engagementRules.$inferInsert).returning();
  await audit(ctx, "create", "engagement_rule", r!.id, undefined, r);
  return { data: r };
} });
route({ method: "GET", path: "/engagement-rules/:id", tag: "Social", scope: "social:read", summary: "Get a rule with its latest firings", handler: async (_r, ctx, p) => {
  const r = await ctx.db.query.engagementRules.findFirst({ where: and(eq(schema.engagementRules.id, p.id!), eq(schema.engagementRules.workspaceId, ctx.workspace.id)) });
  if (!r) throw notFound("Rule");
  const firings = await ctx.db.select().from(schema.ruleFirings).where(eq(schema.ruleFirings.ruleId, r.id)).orderBy(desc(schema.ruleFirings.createdAt)).limit(50);
  return { data: { ...r, firings } };
} });
route({ method: "PATCH", path: "/engagement-rules/:id", tag: "Social", scope: "rules:write", summary: "Edit, enable or disable a rule", body: ruleIn.partial(), handler: async (req, ctx, p) => {
  needRules(ctx);
  const b = await body(req, ruleIn.partial());
  const cur = await ctx.db.query.engagementRules.findFirst({ where: and(eq(schema.engagementRules.id, p.id!), eq(schema.engagementRules.workspaceId, ctx.workspace.id)) });
  if (!cur) throw notFound("Rule");
  validateRule({ trigger: (b.trigger ?? cur.trigger) as never, ...b });
  if (b.actions?.some((a) => a.type === "ai_reply")) social.assertSocial(ctx, "ai");
  const [r] = await ctx.db.update(schema.engagementRules).set({ ...toRow(b), updatedAt: new Date() }).where(eq(schema.engagementRules.id, cur.id)).returning();
  await audit(ctx, "update", "engagement_rule", cur.id, cur, r);
  return { data: r };
} });
route({ method: "DELETE", path: "/engagement-rules/:id", tag: "Social", scope: "rules:write", summary: "Delete a rule", handler: async (_r, ctx, p) => {
  needRules(ctx);
  const cur = await ctx.db.query.engagementRules.findFirst({ where: and(eq(schema.engagementRules.id, p.id!), eq(schema.engagementRules.workspaceId, ctx.workspace.id)) });
  if (!cur) throw notFound("Rule");
  await ctx.db.delete(schema.engagementRules).where(eq(schema.engagementRules.id, cur.id));
  await audit(ctx, "delete", "engagement_rule", cur.id, cur);
} });
const testIn = z.object({ text: z.string().min(1).max(4000), channel: z.string().optional(), trigger: z.enum(["new_comment", "new_dm", "new_review"]).optional(), account_id: z.string().uuid().optional(), object_id: z.string().uuid().optional(), rating: z.number().int().min(1).max(5).optional(), new_contact: z.boolean().optional(), at: z.string().datetime().optional(), rule_ids: z.array(z.string().uuid()).optional() });
route({ method: "POST", path: "/engagement-rules/test", tag: "Social", scope: "social:read", summary: "Dry-run a sample message against the rules — shows classification, matching rules and actions (nothing is sent)", body: testIn, handler: async (req, ctx) => {
  const b = await body(req, testIn);
  return { data: await social.testRules(ctx, { text: b.text, channel: b.channel, trigger: b.trigger, accountId: b.account_id, objectId: b.object_id, rating: b.rating, newContact: b.new_contact, at: b.at }, b.rule_ids) };
} });

/* ---------------- saved replies (SOC-024) — same store as canned replies ---------------- */

const savedIn = z.object({ title: z.string().min(1).max(120), shortcut: z.string().regex(/^\/[\w-]+$/, "Shortcut must look like /price"), body: z.string().min(1).max(4000), channels: z.array(z.string()).default([]), tags: z.array(z.string()).default([]), language: z.enum(["en", "bn", "banglish"]).default("en") });
route({ method: "GET", path: "/saved-replies", tag: "Social", scope: "read:messages", summary: "Saved replies with variables (?filter[channel]=facebook_comment&q=)", handler: async (req, ctx) => {
  const f = filterParams(req);
  const q = req.nextUrl.searchParams.get("q");
  const S = schema.cannedReplies;
  const rows = await ctx.db.select().from(S).where(and(eq(S.workspaceId, ctx.workspace.id), f.channel ? or(sql`cardinality(${S.channels}) = 0`, sql`${f.channel} = ANY(${S.channels})`) : undefined, q ? or(ilike(S.title, `%${q}%`), ilike(S.shortcut, `%${q}%`), ilike(S.body, `%${q}%`)) : undefined)).orderBy(S.shortcut);
  return { data: rows };
} });
route({ method: "POST", path: "/saved-replies", tag: "Social", scope: "write:messages", summary: "Create a saved reply ({{first_name}}, {{project_name}} variables are detected)", body: savedIn, handler: async (req, ctx) => {
  const b = await body(req, savedIn);
  const dupe = await ctx.db.query.cannedReplies.findFirst({ where: and(eq(schema.cannedReplies.workspaceId, ctx.workspace.id), eq(schema.cannedReplies.shortcut, b.shortcut)) });
  if (dupe) throw new ApiError(409, "conflict", `Shortcut ${b.shortcut} is already used`);
  const [r] = await ctx.db.insert(schema.cannedReplies).values({ workspaceId: ctx.workspace.id, ...b, variables: extractVariables(b.body) }).returning();
  return { data: r };
} });
route({ method: "PATCH", path: "/saved-replies/:id", tag: "Social", scope: "write:messages", summary: "Edit a saved reply", body: savedIn.partial(), handler: async (req, ctx, p) => {
  const b = await body(req, savedIn.partial());
  const [r] = await ctx.db.update(schema.cannedReplies).set({ ...b, ...(b.body ? { variables: extractVariables(b.body) } : {}), updatedAt: new Date() }).where(and(eq(schema.cannedReplies.id, p.id!), eq(schema.cannedReplies.workspaceId, ctx.workspace.id))).returning();
  if (!r) throw notFound("Saved reply");
  return { data: r };
} });
route({ method: "DELETE", path: "/saved-replies/:id", tag: "Social", scope: "write:messages", summary: "Delete a saved reply", handler: async (_r, ctx, p) => {
  await ctx.db.delete(schema.cannedReplies).where(and(eq(schema.cannedReplies.id, p.id!), eq(schema.cannedReplies.workspaceId, ctx.workspace.id)));
} });

/* ---------------- knowledge base (SOC-AI-003) ---------------- */

const kbIn = z.object({ question: z.string().min(2).max(500), answer: z.string().min(1).max(4000), scope: z.string().max(120).nullable().optional(), social_account_id: z.string().uuid().nullable().optional(), language: z.enum(["en", "bn", "banglish"]).default("en"), tags: z.array(z.string()).default([]), is_active: z.boolean().default(true) });
const kbRow = (b: Partial<z.infer<typeof kbIn>>) => ({ ...(b.question ? { question: b.question } : {}), ...(b.answer ? { answer: b.answer } : {}), ...(b.scope !== undefined ? { scope: b.scope } : {}), ...(b.social_account_id !== undefined ? { socialAccountId: b.social_account_id } : {}), ...(b.language ? { language: b.language } : {}), ...(b.tags ? { tags: b.tags } : {}), ...(b.is_active !== undefined ? { isActive: b.is_active } : {}) });
route({ method: "GET", path: "/knowledge-base", tag: "Social", scope: "social:read", summary: "Knowledge base entries used to ground AI replies (?q=)", handler: async (req, ctx) => {
  const q = req.nextUrl.searchParams.get("q");
  const K = schema.knowledgeEntries;
  return { data: await ctx.db.select().from(K).where(and(eq(K.workspaceId, ctx.workspace.id), q ? or(ilike(K.question, `%${q}%`), ilike(K.answer, `%${q}%`)) : undefined)).orderBy(desc(K.updatedAt)) };
} });
route({ method: "POST", path: "/knowledge-base", tag: "Social", scope: "rules:write", summary: "Add a knowledge entry (prices, payment plans, locations, FAQs)", body: kbIn, handler: async (req, ctx) => {
  needRules(ctx);
  const b = await body(req, kbIn);
  const [r] = await ctx.db.insert(schema.knowledgeEntries).values({ workspaceId: ctx.workspace.id, ...kbRow(b), question: b.question, answer: b.answer, createdBy: ctx.user?.id ?? null }).returning();
  await audit(ctx, "create", "knowledge_entry", r!.id, undefined, r);
  return { data: r };
} });
route({ method: "PATCH", path: "/knowledge-base/:id", tag: "Social", scope: "rules:write", summary: "Edit a knowledge entry", body: kbIn.partial(), handler: async (req, ctx, p) => {
  needRules(ctx);
  const b = await body(req, kbIn.partial());
  const [r] = await ctx.db.update(schema.knowledgeEntries).set({ ...kbRow(b), updatedAt: new Date() }).where(and(eq(schema.knowledgeEntries.id, p.id!), eq(schema.knowledgeEntries.workspaceId, ctx.workspace.id))).returning();
  if (!r) throw notFound("Knowledge entry");
  return { data: r };
} });
route({ method: "DELETE", path: "/knowledge-base/:id", tag: "Social", scope: "rules:write", summary: "Delete a knowledge entry", handler: async (_r, ctx, p) => {
  needRules(ctx);
  await ctx.db.delete(schema.knowledgeEntries).where(and(eq(schema.knowledgeEntries.id, p.id!), eq(schema.knowledgeEntries.workspaceId, ctx.workspace.id)));
} });

/* ---------------- AI (SOC-AI-002…004) ---------------- */

route({ method: "POST", path: "/ai/suggest-reply", tag: "Social", scope: "social:write", summary: "2–3 reply suggestions grounded in the knowledge base, brand voice and contact history (never sent automatically)", body: z.object({ conversation_id: z.string().uuid(), mode: z.enum(["public", "private"]).optional() }), handler: async (req, ctx) => {
  const b = await body(req, z.object({ conversation_id: z.string().uuid(), mode: z.enum(["public", "private"]).optional() }));
  const conv = await ctx.db.query.conversations.findFirst({ where: and(eq(schema.conversations.id, b.conversation_id), eq(schema.conversations.workspaceId, ctx.workspace.id)) });
  if (!conv) throw notFound("Conversation");
  const { suggestReplies } = await import("@/lib/ai/social");
  return { data: await suggestReplies(ctx, conv.id, { mode: b.mode }) };
} });

/* ---------------- moderation log & blocklist (SOC-063) ---------------- */

route({ method: "GET", path: "/moderation/log", tag: "Social", scope: "social:read", summary: "Moderation log: who hid / deleted what and why (?filter[actor]=rule|user|ai&filter[action]=hide)", handler: async (req, ctx) => {
  const f = filterParams(req);
  const M = schema.moderationEvents;
  const rows = await ctx.db.select({ e: M, body: schema.comments.body, author: schema.comments.authorName, channel: schema.comments.channel, conversationId: schema.comments.conversationId, isHidden: schema.comments.isHidden }).from(M).innerJoin(schema.comments, eq(schema.comments.id, M.commentId))
    .where(and(eq(M.workspaceId, ctx.workspace.id), f.actor ? eq(M.actorType, f.actor) : undefined, f.action ? eq(M.action, f.action) : undefined)).orderBy(desc(M.createdAt)).limit(300);
  return { data: rows.map((r) => ({ ...r.e, comment: { body: r.body, author: r.author, channel: r.channel, conversationId: r.conversationId, isHidden: r.isHidden } })) };
} });
route({ method: "POST", path: "/moderation/:id/undo", tag: "Social", scope: "social:moderate", summary: "Undo a hide (unhides on the platform)", handler: async (_r, ctx, p) => { await social.undoModeration(ctx, p.id!); return { ok: true }; } });
route({ method: "GET", path: "/social/blocklist", tag: "Social", scope: "social:read", summary: "Blocked authors", handler: async (_r, ctx) => ({ data: await ctx.db.select().from(schema.socialBlocklist).where(eq(schema.socialBlocklist.workspaceId, ctx.workspace.id)).orderBy(desc(schema.socialBlocklist.createdAt)) }) });
route({ method: "DELETE", path: "/social/blocklist/:id", tag: "Social", scope: "social:moderate", summary: "Unblock an author", handler: async (_r, ctx, p) => {
  social.assertSocial(ctx, "moderate");
  await ctx.db.delete(schema.socialBlocklist).where(and(eq(schema.socialBlocklist.id, p.id!), eq(schema.socialBlocklist.workspaceId, ctx.workspace.id)));
  await audit(ctx, "social.unblock", "social_blocklist", p.id!);
} });

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

route({ method: "GET", path: "/reports/engagement", tag: "Social", scope: "read:reports", summary: "Engagement report: volume, replied %, median/p90 first response, resolution, by channel/account/agent/day, sentiment, intents, top posts/ads with leads & won revenue, automation impact (?from=&to=&group_by=&format=csv)", handler: async (req, ctx) => {
  social.assertSocial(ctx, "analytics");
  const sp = req.nextUrl.searchParams;
  const to = sp.get("to") ? new Date(sp.get("to")!) : new Date();
  const from = sp.get("from") ? new Date(sp.get("from")!) : new Date(to.getTime() - 30 * 86400000);
  if (Number.isNaN(from.getTime()) || Number.isNaN(to.getTime()) || from > to) throw new ApiError(422, "validation_failed", "Invalid date range");
  const groupBy = (["channel", "account", "agent", "day"].includes(sp.get("group_by") ?? "") ? sp.get("group_by") : "channel") as "channel" | "account" | "agent" | "day";
  const r = await social.engagementReport(ctx, from, to, groupBy);
  if (sp.get("format") === "csv") {
    const esc = (v: unknown) => { const s = v == null ? "" : String(v); return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s; };
    const cols = ["key", "conversations", "inbound", "replied", "repliedPct", "resolved", "hidden", "negative", "leads", "automatedPct", "medianFirstResponseS", "p90FirstResponseS", "medianResolutionS"] as const;
    const lines = [cols.join(","), ...[...r.groups, r.total].map((g) => cols.map((c) => esc(typeof g[c] === "number" ? Math.round((g[c] as number) * 10) / 10 : g[c])).join(","))];
    lines.push("", "post_or_ad,type,campaign,comments,negative_pct,leads,won,revenue", ...r.topObjects.slice(0, 50).map((o) => [o.caption, o.type, o.campaign, o.comments, Math.round(o.negativeShare), o.leads, o.won, o.revenue].map(esc).join(",")));
    return new Response(lines.join("\n"), { headers: { "Content-Type": "text/csv; charset=utf-8", "Content-Disposition": `attachment; filename="engagement-${from.toISOString().slice(0, 10)}-${to.toISOString().slice(0, 10)}.csv"` } });
  }
  return { data: { from, to, groupBy, ...r } };
} });
route({ method: "GET", path: "/reports/engagement/daily", tag: "Social", scope: "read:reports", summary: "Daily engagement rollups (engagement_metrics_daily)", handler: async (req, ctx) => {
  social.assertSocial(ctx, "analytics");
  const days = Math.min(Number(req.nextUrl.searchParams.get("days") ?? 30) || 30, 366);
  const since = new Date(Date.now() - days * 86400000).toISOString().slice(0, 10);
  return { data: await ctx.db.select().from(schema.engagementMetricsDaily).where(and(eq(schema.engagementMetricsDaily.workspaceId, ctx.workspace.id), gte(schema.engagementMetricsDaily.date, since))).orderBy(schema.engagementMetricsDaily.date) };
} });

/* ---------------- inbox counters (sidebar badges) ---------------- */

route({ method: "GET", path: "/inbox/counts", tag: "Social", scope: "read:messages", internal: true, summary: "Unread / unanswered / SLA counters for the inbox rail", handler: async (_r, ctx) => {
  const C = schema.conversations;
  const allowed = await social.allowedAccountIds(ctx);
  const socialView = can(ctx.perms, "social", "view");
  const base = and(eq(C.workspaceId, ctx.workspace.id), socialView ? undefined : eq(C.kind, "dm"), allowed ? or(isNull(C.socialAccountId), inArray(C.socialAccountId, allowed)) : undefined);
  const [r] = await ctx.db.select({
    open: sql<number>`count(*) FILTER (WHERE ${C.status} IN ('open','pending'))::int`,
    mine: sql<number>`count(*) FILTER (WHERE ${C.status} IN ('open','pending') AND ${C.assigneeId} = ${ctx.user?.id ?? null})::int`,
    unassigned: sql<number>`count(*) FILTER (WHERE ${C.status} IN ('open','pending') AND ${C.assigneeId} IS NULL)::int`,
    unanswered: sql<number>`count(*) FILTER (WHERE ${C.status} IN ('open','pending') AND ${C.firstResponseAt} IS NULL AND ${C.lastInboundAt} IS NOT NULL)::int`,
    breached: sql<number>`count(*) FILTER (WHERE ${C.slaBreachedAt} IS NOT NULL AND ${C.firstResponseAt} IS NULL AND ${C.status} IN ('open','pending'))::int`,
    comments: sql<number>`count(*) FILTER (WHERE ${C.kind} = 'comment_thread' AND ${C.status} IN ('open','pending'))::int`,
    reviews: sql<number>`count(*) FILTER (WHERE ${C.kind} = 'review' AND ${C.status} IN ('open','pending'))::int`,
    dms: sql<number>`count(*) FILTER (WHERE ${C.kind} = 'dm' AND ${C.status} IN ('open','pending'))::int`,
    negative: sql<number>`count(*) FILTER (WHERE ${C.sentiment} = 'negative' AND ${C.status} IN ('open','pending'))::int`,
    snoozed: sql<number>`count(*) FILTER (WHERE ${C.status} = 'snoozed')::int`,
  }).from(C).where(base);
  return { data: r };
} });
