/** Ads, conversions, analytics/reports, forms & pages, content & assets, AI. */
import { z } from "zod";
import { and, asc, desc, eq, gte, lte, sql } from "drizzle-orm";
import { schema } from "@/db";
import { route } from "../router";
import { ApiError, body, forbidden, notFound } from "@/lib/api";
import { audit } from "@/lib/audit";
import { can } from "@/lib/rbac";
import { randomToken, slugify } from "@/lib/util";
import { attribution, campaignPerformance, funnel, parseFilters, repPerformance } from "@/lib/services/analytics";
import { queueConversions } from "@/lib/services/conversions";
import { REPORT_SECTIONS, ensureShareToken, renderReportPdf, sendReportEmail } from "@/lib/services/reports";
import { transitionPost } from "@/lib/services/content";
import { abResults } from "@/lib/services/forms";

/* ---------------- ads (ADS-001…008) ---------------- */
route({ method: "GET", path: "/ad-accounts", tag: "Ads", scope: "read:ads", summary: "List connected ad accounts with currency and timezone", handler: async (_r, ctx) => ({ data: await ctx.db.select().from(schema.adAccounts).where(eq(schema.adAccounts.workspaceId, ctx.workspace.id)).orderBy(asc(schema.adAccounts.provider)) }) });
route({ method: "PATCH", path: "/ad-accounts/:id", tag: "Ads", scope: "write:ads", summary: "Set the monthly budget plan used for pacing alerts", body: z.object({ monthly_budget: z.number().int().nonnegative().nullable() }), handler: async (req, ctx, p) => {
  if (!can(ctx.perms, "ads", "edit")) throw forbidden();
  const b = await body(req, z.object({ monthly_budget: z.number().int().nonnegative().nullable() }));
  const [r] = await ctx.db.update(schema.adAccounts).set({ monthlyBudget: b.monthly_budget, updatedAt: new Date() }).where(and(eq(schema.adAccounts.id, p.id!), eq(schema.adAccounts.workspaceId, ctx.workspace.id))).returning();
  if (!r) throw notFound("Ad account");
  await audit(ctx, "update", "ad_account", r.id, undefined, { monthlyBudget: b.monthly_budget });
  return { data: r };
} });
route({ method: "GET", path: "/ads/metrics", tag: "Ads", scope: "read:ads", summary: "Ad metrics ?from=&to=&level=campaign|adset|ad|day", handler: async (req, ctx) => {
  const sp = req.nextUrl.searchParams;
  const from = sp.get("from") ?? new Date(Date.now() - 30 * 86400000).toISOString().slice(0, 10);
  const to = sp.get("to") ?? new Date().toISOString().slice(0, 10);
  const level = sp.get("level") ?? "campaign";
  const groupCol = level === "ad" ? schema.ads.id : level === "adset" ? schema.adSets.id : level === "day" ? schema.adMetricsDaily.date : schema.campaigns.id;
  const nameCol = level === "ad" ? schema.ads.name : level === "adset" ? schema.adSets.name : level === "day" ? schema.adMetricsDaily.date : schema.campaigns.name;
  const rows = await ctx.db.select({ key: sql<string>`${groupCol}::text`, name: sql<string>`max(${nameCol}::text)`, provider: sql<string>`max(${schema.ads.provider})`, spend: sql<number>`sum(${schema.adMetricsDaily.spend})::bigint`, impressions: sql<number>`sum(${schema.adMetricsDaily.impressions})::int`, clicks: sql<number>`sum(${schema.adMetricsDaily.clicks})::int`, leads: sql<number>`sum(${schema.adMetricsDaily.leads})::int`, conversions: sql<number>`sum(${schema.adMetricsDaily.conversions})::int` })
    .from(schema.adMetricsDaily).innerJoin(schema.ads, eq(schema.ads.id, schema.adMetricsDaily.adId)).innerJoin(schema.adSets, eq(schema.adSets.id, schema.ads.adSetId)).innerJoin(schema.campaigns, eq(schema.campaigns.id, schema.adSets.campaignId))
    .where(and(eq(schema.adMetricsDaily.workspaceId, ctx.workspace.id), gte(schema.adMetricsDaily.date, from), lte(schema.adMetricsDaily.date, to))).groupBy(groupCol).orderBy(level === "day" ? asc(groupCol) : desc(sql`4`));
  return { data: rows.map((r) => ({ ...r, spend: Number(r.spend), cpl: r.leads ? Number(r.spend) / r.leads : null, ctr: r.impressions ? (r.clicks / r.impressions) * 100 : 0 })), currency_note: "spend in minor units of the ad account currency" };
} });
route({ method: "GET", path: "/ads/performance", tag: "Ads", scope: "read:ads", internal: true, summary: "Spend vs pipeline by campaign", handler: async (req, ctx) => ({ data: await campaignPerformance(ctx, parseFilters(req.nextUrl.searchParams)) }) });
route({ method: "GET", path: "/ads/pacing", tag: "Ads", scope: "read:ads", summary: "Budget pacing per ad account (projected month-end vs plan)", handler: async (_r, ctx) => {
  const { checkPacing } = await import("@/lib/ai/features");
  const rows = await checkPacing(ctx);
  return { data: rows.map((r) => ({ accountId: r.account.id, name: r.account.name, provider: r.account.provider, currency: r.account.currency, spent: r.spent, projected: r.projected, budget: r.budget, diffPct: r.diffPct, status: r.status })) };
} });
route({ method: "POST", path: "/ads/refresh", tag: "Ads", scope: "read:ads", summary: "Manual refresh of ad metrics for all connected ad accounts", handler: async (_r, ctx) => {
  const { syncIntegration } = await import("@/connectors");
  const ints = await ctx.db.select().from(schema.integrations).where(and(eq(schema.integrations.workspaceId, ctx.workspace.id), eq(schema.integrations.status, "connected")));
  const out: Record<string, string> = {};
  for (const i of ints.filter((x) => ["meta", "google_ads", "tiktok", "linkedin"].includes(x.provider))) {
    try { out[i.provider] = (await syncIntegration(ctx, i)).summary; } catch (e) { out[i.provider] = `Error: ${(e as Error).message}`; }
  }
  return { data: out };
} });
route({ method: "POST", path: "/ads/actions", tag: "Ads", scope: "write:ads", summary: "Propose a write action (pause/resume/budget) — goes to the approval queue", body: z.object({ kind: z.enum(["pause_ad", "resume_ad", "change_budget"]), campaign_id: z.string().uuid(), change_pct: z.number().min(-90).max(200).optional(), reason: z.string().optional() }), handler: async (req, ctx) => {
  if (!can(ctx.perms, "ai_spend", "view") && !can(ctx.perms, "ads", "edit")) throw forbidden();
  const b = await body(req, z.object({ kind: z.enum(["pause_ad", "resume_ad", "change_budget"]), campaign_id: z.string().uuid(), change_pct: z.number().min(-90).max(200).optional(), reason: z.string().optional() }));
  const camp = await ctx.db.query.campaigns.findFirst({ where: and(eq(schema.campaigns.id, b.campaign_id), eq(schema.campaigns.workspaceId, ctx.workspace.id)) });
  if (!camp) throw notFound("Campaign");
  if (b.kind === "change_budget" && !b.change_pct) throw new ApiError(422, "validation_failed", "change_pct is required for budget changes");
  const { proposeAction } = await import("@/lib/ai/features");
  return { data: await proposeAction(ctx, { agent: ctx.actor.type === "user" ? `user:${ctx.actor.name}` : ctx.actor.name, kind: b.kind, proposedAction: { campaignId: camp.id, campaignName: camp.name, provider: camp.provider, changePct: b.change_pct }, reasoning: b.reason ?? "Manual request", expectedImpact: b.kind === "change_budget" ? `${b.change_pct! > 0 ? "+" : ""}${b.change_pct}% budget` : b.kind.replace("_", " ") }) };
} });
route({ method: "GET", path: "/conversions", tag: "Conversions", scope: "read:ads", summary: "Conversion sync log", handler: async (req, ctx) => {
  const status = req.nextUrl.searchParams.get("status");
  return { data: await ctx.db.select().from(schema.conversionSyncs).where(and(eq(schema.conversionSyncs.workspaceId, ctx.workspace.id), status ? eq(schema.conversionSyncs.status, status) : undefined)).orderBy(desc(schema.conversionSyncs.createdAt)).limit(300) };
} });
route({ method: "POST", path: "/conversions", tag: "Conversions", scope: "write:conversions", summary: "Send a manual / custom conversion for a contact", body: z.object({ contact_id: z.string().uuid(), deal_id: z.string().uuid().optional(), event_name: z.string().min(1), value: z.number().int().nonnegative().optional(), providers: z.array(z.enum(["meta", "google_ads", "tiktok", "linkedin"])).optional() }), handler: async (req, ctx) => {
  const b = await body(req, z.object({ contact_id: z.string().uuid(), deal_id: z.string().uuid().optional(), event_name: z.string().min(1), value: z.number().int().nonnegative().optional(), providers: z.array(z.enum(["meta", "google_ads", "tiktok", "linkedin"])).optional() }));
  const ids = await queueConversions(ctx, { contactId: b.contact_id, dealId: b.deal_id ?? `${b.contact_id}:manual:${Date.now()}` as never, eventName: b.event_name, value: b.value, providers: b.providers });
  if (!ids.length) throw new ApiError(409, "not_connected", "No connected ad platform to send to (or this event was already sent)");
  return { data: { queued: ids } };
} });
route({ method: "GET", path: "/conversions/:id", tag: "Conversions", scope: "read:ads", summary: "Get a conversion sync record", handler: async (_r, ctx, p) => {
  const r = await ctx.db.query.conversionSyncs.findFirst({ where: and(eq(schema.conversionSyncs.id, p.id!), eq(schema.conversionSyncs.workspaceId, ctx.workspace.id)) });
  if (!r) throw notFound("Conversion");
  return { data: r };
} });
route({ method: "POST", path: "/conversions/:id/retry", tag: "Conversions", scope: "write:conversions", internal: true, summary: "Retry a failed conversion", handler: async (_r, ctx, p) => {
  const r = await ctx.db.query.conversionSyncs.findFirst({ where: and(eq(schema.conversionSyncs.id, p.id!), eq(schema.conversionSyncs.workspaceId, ctx.workspace.id)) });
  if (!r) throw notFound("Conversion");
  const integ = await ctx.db.query.integrations.findFirst({ where: and(eq(schema.integrations.workspaceId, ctx.workspace.id), eq(schema.integrations.provider, r.provider === "google" ? "google_ads" : r.provider)) });
  if (!integ) throw new ApiError(409, "not_connected", "Integration not connected");
  await ctx.db.update(schema.conversionSyncs).set({ status: "pending" }).where(eq(schema.conversionSyncs.id, r.id));
  const { sendConversion } = await import("@/lib/services/conversions");
  await sendConversion(ctx, r.id, integ.id);
  return { data: await ctx.db.query.conversionSyncs.findFirst({ where: eq(schema.conversionSyncs.id, r.id) }) };
} });
route({ method: "GET", path: "/anomalies", tag: "AI", scope: "read:ads", internal: true, summary: "Anomaly & pacing alerts", handler: async (_r, ctx) => ({ data: await ctx.db.select().from(schema.anomalies).where(eq(schema.anomalies.workspaceId, ctx.workspace.id)).orderBy(desc(schema.anomalies.createdAt)).limit(100) }) });
route({ method: "POST", path: "/anomalies/:id/ack", tag: "AI", scope: "read:ads", internal: true, summary: "Acknowledge an alert", handler: async (_r, ctx, p) => { await ctx.db.update(schema.anomalies).set({ acknowledgedAt: new Date() }).where(and(eq(schema.anomalies.id, p.id!), eq(schema.anomalies.workspaceId, ctx.workspace.id))); } });

/* ---------------- reports (ANL) ---------------- */
route({ method: "GET", path: "/reports/funnel", tag: "Reports", scope: "read:reports", summary: "Funnel with cost per stage (?days=&from=&to=&source=&campaign=&project=&rep=)", handler: async (req, ctx) => {
  const f = parseFilters(req.nextUrl.searchParams);
  if (ctx.perms.reports === "V:own" && ctx.user) f.rep = ctx.user.id;
  return { data: await funnel(ctx, f) };
} });
route({ method: "GET", path: "/reports/attribution", tag: "Reports", scope: "read:reports", summary: "Attribution (?model=first_touch|last_touch|linear|time_decay|position_based&group=channel|campaign)", handler: async (req, ctx) => {
  const sp = req.nextUrl.searchParams;
  return { data: await attribution(ctx, parseFilters(sp), sp.get("model") ?? ctx.workspace.settings?.attributionModel ?? "last_touch", sp.get("group") === "campaign" ? "campaign" : "channel") };
} });
route({ method: "GET", path: "/reports/reps", tag: "Reports", scope: "read:reports", summary: "Rep leaderboard", handler: async (req, ctx) => {
  const rows = await repPerformance(ctx, parseFilters(req.nextUrl.searchParams));
  return { data: ctx.perms.reports === "V:own" ? rows.filter((r) => r.userId === ctx.user?.id) : rows };
} });
const reportIn = z.object({ name: z.string().min(1), config: z.object({ days: z.number().int().min(1).max(730).optional(), from: z.string().optional(), to: z.string().optional(), sections: z.array(z.string()).min(1), filters: z.record(z.string()).optional(), whiteLabel: z.boolean().optional(), model: z.string().optional() }), schedule: z.enum(["weekly_mon", "monthly_1"]).nullable().optional(), recipients: z.array(z.string().email()).default([]) });
route({ method: "GET", path: "/reports/saved", tag: "Reports", scope: "read:reports", summary: "Saved reports", handler: async (_r, ctx) => ({ data: await ctx.db.select().from(schema.savedReports).where(eq(schema.savedReports.workspaceId, ctx.workspace.id)).orderBy(desc(schema.savedReports.updatedAt)), sections: REPORT_SECTIONS }) });
route({ method: "POST", path: "/reports/saved", tag: "Reports", scope: "read:reports", body: reportIn, summary: "Save a report (optional weekly/monthly email delivery)", handler: async (req, ctx) => {
  if (!can(ctx.perms, "reports", "edit")) throw forbidden();
  const b = await body(req, reportIn);
  const [r] = await ctx.db.insert(schema.savedReports).values({ workspaceId: ctx.workspace.id, name: b.name, config: b.config, schedule: b.schedule ?? null, recipients: b.recipients, shareToken: randomToken(18), createdBy: ctx.user?.id ?? null }).returning();
  await audit(ctx, "create", "report", r!.id, undefined, { name: b.name, schedule: b.schedule });
  return { data: r };
} });
route({ method: "PATCH", path: "/reports/saved/:id", tag: "Reports", scope: "read:reports", body: reportIn.partial(), summary: "Update a saved report", handler: async (req, ctx, p) => {
  if (!can(ctx.perms, "reports", "edit")) throw forbidden();
  const b = await body(req, reportIn.partial());
  const [r] = await ctx.db.update(schema.savedReports).set({ ...(b.name ? { name: b.name } : {}), ...(b.config ? { config: b.config } : {}), ...(b.schedule !== undefined ? { schedule: b.schedule } : {}), ...(b.recipients ? { recipients: b.recipients } : {}), updatedAt: new Date() }).where(and(eq(schema.savedReports.id, p.id!), eq(schema.savedReports.workspaceId, ctx.workspace.id))).returning();
  if (!r) throw notFound("Report");
  return { data: r };
} });
route({ method: "DELETE", path: "/reports/saved/:id", tag: "Reports", scope: "read:reports", summary: "Delete a saved report", handler: async (_r, ctx, p) => {
  if (!can(ctx.perms, "reports", "edit")) throw forbidden();
  await ctx.db.delete(schema.savedReports).where(and(eq(schema.savedReports.id, p.id!), eq(schema.savedReports.workspaceId, ctx.workspace.id)));
} });
route({ method: "POST", path: "/reports/saved/:id/send", tag: "Reports", scope: "read:reports", summary: "Email the report now", handler: async (_r, ctx, p) => {
  await sendReportEmail(ctx, p.id!);
  return { data: { sent: true } };
} });
route({ method: "GET", path: "/reports/saved/:id/pdf", tag: "Reports", scope: "read:reports", summary: "Download the report as PDF", handler: async (_r, ctx, p) => {
  const r = await ctx.db.query.savedReports.findFirst({ where: and(eq(schema.savedReports.id, p.id!), eq(schema.savedReports.workspaceId, ctx.workspace.id)) });
  if (!r) throw notFound("Report");
  const pdf = await renderReportPdf(ctx, r.name, r.config);
  return new Response(Buffer.from(pdf), { headers: { "Content-Type": "application/pdf", "Content-Disposition": `inline; filename="${slugify(r.name)}.pdf"` } });
} });
route({ method: "POST", path: "/reports/saved/:id/share", tag: "Reports", scope: "read:reports", internal: true, summary: "Get the share link", handler: async (_r, ctx, p) => ({ data: { token: await ensureShareToken(ctx, p.id!) } }) });

/* ---------------- forms & pages (PAGE) ---------------- */
const fieldSchema = z.object({ key: z.string().regex(/^[a-z][a-z0-9_]*$/), label: z.string(), type: z.enum(["text", "email", "phone", "number", "select", "textarea", "checkbox", "hidden"]), required: z.boolean().optional(), options: z.array(z.string()).optional(), mapTo: z.string().optional() });
const formSchemaZ = z.object({ kind: z.literal("form"), title: z.string(), description: z.string().optional(), fields: z.array(fieldSchema).min(1), submitLabel: z.string(), successMessage: z.string(), consent: z.array(z.object({ channel: z.string(), label: z.string() })).optional(), captcha: z.boolean().optional(), createDeal: z.boolean().optional(), project: z.string().optional() });
const blockSchema = z.object({ id: z.string(), type: z.enum(["hero", "features", "text", "image", "form", "cta", "testimonial", "faq", "gallery"]), props: z.record(z.unknown()) });
const pageSchemaZ = z.object({ kind: z.literal("page"), title: z.string(), blocks: z.array(blockSchema), theme: z.object({ accent: z.string().optional(), dark: z.boolean().optional() }).optional(), formId: z.string().uuid().optional(), seo: z.object({ title: z.string().optional(), description: z.string().optional() }).optional() });
const formIn = z.object({ name: z.string().min(1), slug: z.string().regex(/^[a-z0-9-]+$/).optional(), type: z.enum(["form", "page"]), schema: z.union([formSchemaZ, pageSchemaZ]), variants: z.array(z.object({ key: z.string(), weight: z.number().min(0), blocks: z.array(blockSchema) })).optional(), domain: z.string().nullable().optional(), status: z.enum(["draft", "published"]).optional(), pixels: z.object({ metaPixelId: z.string().optional(), ga4Id: z.string().optional(), gtmId: z.string().optional() }).optional() });
route({ method: "GET", path: "/forms", tag: "Forms", scope: "read:forms", summary: "List forms and landing pages", handler: async (_r, ctx) => {
  const rows = await ctx.db.select().from(schema.forms).where(eq(schema.forms.workspaceId, ctx.workspace.id)).orderBy(desc(schema.forms.updatedAt));
  const subs = await ctx.db.select({ f: schema.submissions.formId, n: sql<number>`count(*)::int` }).from(schema.submissions).where(eq(schema.submissions.workspaceId, ctx.workspace.id)).groupBy(schema.submissions.formId);
  return { data: rows.map((f) => ({ ...f, submissions: subs.find((s) => s.f === f.id)?.n ?? 0 })) };
} });
route({ method: "POST", path: "/forms", tag: "Forms", scope: "write:forms", body: formIn, summary: "Create a form or landing page", handler: async (req, ctx) => {
  const b = await body(req, formIn);
  if (b.type !== b.schema.kind) throw new ApiError(422, "validation_failed", "type and schema.kind must match");
  const slug = b.slug ?? slugify(b.name);
  const [r] = await ctx.db.insert(schema.forms).values({ workspaceId: ctx.workspace.id, name: b.name, slug, type: b.type, schema: b.schema as never, variants: (b.variants ?? []) as never, domain: b.domain ?? null, status: b.status ?? "draft", publishedVersion: b.status === "published" ? 1 : 0, pixels: b.pixels ?? {}, createdBy: ctx.user?.id ?? null }).onConflictDoNothing().returning();
  if (!r) throw new ApiError(409, "conflict", `Slug "${slug}" is already used`);
  await audit(ctx, "create", "form", r.id, undefined, { name: b.name, type: b.type });
  return { data: r };
} });
route({ method: "GET", path: "/forms/:id", tag: "Forms", scope: "read:forms", summary: "Get a form/page with A/B results", handler: async (_r, ctx, p) => {
  const f = await ctx.db.query.forms.findFirst({ where: and(eq(schema.forms.id, p.id!), eq(schema.forms.workspaceId, ctx.workspace.id)) });
  if (!f) throw notFound("Form");
  const recent = await ctx.db.select().from(schema.submissions).where(eq(schema.submissions.formId, f.id)).orderBy(desc(schema.submissions.createdAt)).limit(50);
  return { data: { ...f, ab: abResults(f.stats), recent } };
} });
route({ method: "PATCH", path: "/forms/:id", tag: "Forms", scope: "write:forms", body: formIn.partial(), summary: "Update / publish a form or page", handler: async (req, ctx, p) => {
  const b = await body(req, formIn.partial());
  const cur = await ctx.db.query.forms.findFirst({ where: and(eq(schema.forms.id, p.id!), eq(schema.forms.workspaceId, ctx.workspace.id)) });
  if (!cur) throw notFound("Form");
  if (b.domain) {
    const taken = await ctx.db.query.forms.findFirst({ where: and(eq(schema.forms.domain, b.domain.toLowerCase())) });
    if (taken && taken.id !== cur.id) throw new ApiError(409, "conflict", "That domain is already attached to another page");
  }
  const publishing = b.status === "published";
  const [r] = await ctx.db.update(schema.forms).set({
    ...(b.name ? { name: b.name } : {}), ...(b.slug ? { slug: b.slug } : {}), ...(b.schema ? { schema: b.schema as never } : {}), ...(b.variants ? { variants: b.variants as never } : {}),
    ...(b.domain !== undefined ? { domain: b.domain ? b.domain.toLowerCase().replace(/^https?:\/\//, "").replace(/\/.*$/, "") : null } : {}), ...(b.pixels ? { pixels: b.pixels } : {}),
    ...(b.status ? { status: b.status } : {}), ...(publishing ? { publishedVersion: cur.publishedVersion + 1 } : {}), updatedAt: new Date(),
  }).where(eq(schema.forms.id, cur.id)).returning();
  await audit(ctx, publishing ? "publish" : "update", "form", cur.id, undefined, { name: r!.name, version: r!.publishedVersion });
  return { data: r };
} });
route({ method: "DELETE", path: "/forms/:id", tag: "Forms", scope: "write:forms", summary: "Delete a form/page", handler: async (_r, ctx, p) => {
  await ctx.db.delete(schema.forms).where(and(eq(schema.forms.id, p.id!), eq(schema.forms.workspaceId, ctx.workspace.id)));
  await audit(ctx, "delete", "form", p.id!);
} });

/* ---------------- content & social (CNT) ---------------- */
const postIn = z.object({ channels: z.array(z.enum(["facebook", "instagram", "linkedin", "tiktok"])).min(1), campaign: z.string().optional(), body: z.string().min(1).max(5000), media: z.array(z.object({ assetId: z.string().optional(), url: z.string().url(), type: z.string() })).default([]), scheduled_at: z.string().datetime().nullable().optional() });
route({ method: "GET", path: "/content/posts", tag: "Content", scope: "read:content", summary: "Content calendar posts (?from=&to=)", handler: async (req, ctx) => {
  if (!can(ctx.perms, "content")) throw forbidden();
  const sp = req.nextUrl.searchParams;
  const from = sp.get("from") ? new Date(sp.get("from")!) : new Date(Date.now() - 62 * 86400000);
  const to = sp.get("to") ? new Date(sp.get("to")!) : new Date(Date.now() + 120 * 86400000);
  return { data: await ctx.db.select().from(schema.contentPosts).where(and(eq(schema.contentPosts.workspaceId, ctx.workspace.id), sql`(${schema.contentPosts.scheduledAt} IS NULL OR (${schema.contentPosts.scheduledAt} BETWEEN ${from} AND ${to}))`)).orderBy(asc(schema.contentPosts.scheduledAt)) };
} });
route({ method: "POST", path: "/content/posts", tag: "Content", scope: "write:content", body: postIn, summary: "Create a draft post", handler: async (req, ctx) => {
  if (!can(ctx.perms, "content", "edit")) throw forbidden();
  const b = await body(req, postIn);
  const [r] = await ctx.db.insert(schema.contentPosts).values({ workspaceId: ctx.workspace.id, channels: b.channels, campaign: b.campaign ?? null, body: b.body, media: b.media, scheduledAt: b.scheduled_at ? new Date(b.scheduled_at) : null, status: "draft", createdBy: ctx.user?.id ?? null }).returning();
  await audit(ctx, "create", "content_post", r!.id, undefined, { channels: b.channels });
  return { data: r };
} });
route({ method: "PATCH", path: "/content/posts/:id", tag: "Content", scope: "write:content", body: postIn.partial(), summary: "Edit or reschedule a post (drag-to-reschedule)", handler: async (req, ctx, p) => {
  if (!can(ctx.perms, "content", "edit") && !can(ctx.perms, "content", "approve")) throw forbidden();
  const b = await body(req, postIn.partial());
  const cur = await ctx.db.query.contentPosts.findFirst({ where: and(eq(schema.contentPosts.id, p.id!), eq(schema.contentPosts.workspaceId, ctx.workspace.id)) });
  if (!cur) throw notFound("Post");
  if (cur.status === "published") throw new ApiError(409, "conflict", "Published posts cannot be edited");
  const contentChanged = b.body !== undefined && b.body !== cur.body;
  const [r] = await ctx.db.update(schema.contentPosts).set({ ...(b.channels ? { channels: b.channels } : {}), ...(b.campaign !== undefined ? { campaign: b.campaign } : {}), ...(b.body ? { body: b.body } : {}), ...(b.media ? { media: b.media } : {}), ...(b.scheduled_at !== undefined ? { scheduledAt: b.scheduled_at ? new Date(b.scheduled_at) : null } : {}),
    ...(contentChanged && ["approved", "scheduled"].includes(cur.status) ? { status: "draft", approverId: null } : {}), updatedAt: new Date() }).where(eq(schema.contentPosts.id, cur.id)).returning();
  await audit(ctx, "update", "content_post", cur.id, { scheduledAt: cur.scheduledAt, status: cur.status }, { scheduledAt: r!.scheduledAt, status: r!.status });
  return { data: r };
} });
route({ method: "POST", path: "/content/posts/:id/transition", tag: "Content", scope: "write:content", summary: "Move a post through draft → in review → approved → scheduled", body: z.object({ to: z.enum(["draft", "in_review", "approved", "scheduled"]), note: z.string().optional() }), handler: async (req, ctx, p) => {
  if (!can(ctx.perms, "content")) throw forbidden();
  const b = await body(req, z.object({ to: z.enum(["draft", "in_review", "approved", "scheduled"]), note: z.string().optional() }));
  return { data: await transitionPost(ctx, p.id!, b.to, b.note) };
} });
route({ method: "DELETE", path: "/content/posts/:id", tag: "Content", scope: "write:content", summary: "Delete a post", handler: async (_r, ctx, p) => {
  if (!can(ctx.perms, "content", "edit")) throw forbidden();
  await ctx.db.delete(schema.contentPosts).where(and(eq(schema.contentPosts.id, p.id!), eq(schema.contentPosts.workspaceId, ctx.workspace.id)));
  await audit(ctx, "delete", "content_post", p.id!);
} });
const assetIn = z.object({ name: z.string().min(1), url: z.string().url(), type: z.enum(["image", "video", "document", "logo"]), folder: z.string().default("General"), tags: z.array(z.string()).default([]) });
route({ method: "GET", path: "/assets", tag: "Content", scope: "read:content", summary: "Asset library", handler: async (_r, ctx) => ({ data: await ctx.db.select().from(schema.assets).where(eq(schema.assets.workspaceId, ctx.workspace.id)).orderBy(desc(schema.assets.createdAt)), brandKits: await ctx.db.select().from(schema.brandKits).where(eq(schema.brandKits.workspaceId, ctx.workspace.id)) }) });
route({ method: "POST", path: "/assets", tag: "Content", scope: "write:content", body: assetIn, summary: "Add an asset (URL or uploaded data URL ≤ 4 MB)", handler: async (req, ctx) => {
  if (!can(ctx.perms, "content", "edit")) throw forbidden();
  const b = await body(req, assetIn.extend({ url: z.string().refine((u) => /^https?:\/\//.test(u) || (/^data:(image|video|application)\//.test(u) && u.length < 5_600_000), "Provide an https URL or a file under 4 MB") }));
  const [r] = await ctx.db.insert(schema.assets).values({ workspaceId: ctx.workspace.id, ...b, sizeBytes: b.url.startsWith("data:") ? Math.round(b.url.length * 0.75) : null, createdBy: ctx.user?.id ?? null }).returning();
  await audit(ctx, "create", "asset", r!.id, undefined, { name: b.name });
  return { data: r };
} });
route({ method: "DELETE", path: "/assets/:id", tag: "Content", scope: "write:content", summary: "Delete an asset", handler: async (_r, ctx, p) => {
  if (!can(ctx.perms, "content", "edit")) throw forbidden();
  await ctx.db.delete(schema.assets).where(and(eq(schema.assets.id, p.id!), eq(schema.assets.workspaceId, ctx.workspace.id)));
} });
const kitIn = z.object({ name: z.string().min(1), logos: z.array(z.string()).default([]), colors: z.array(z.string().regex(/^#[0-9a-fA-F]{6}$/)).default([]), fonts: z.array(z.string()).default([]), voice: z.string().max(2000).optional() });
route({ method: "PUT", path: "/brand-kit", tag: "Content", scope: "write:content", body: kitIn, summary: "Save the brand kit (logos, colours, fonts, voice)", handler: async (req, ctx) => {
  if (!can(ctx.perms, "content", "edit")) throw forbidden();
  const b = await body(req, kitIn);
  const cur = await ctx.db.query.brandKits.findFirst({ where: eq(schema.brandKits.workspaceId, ctx.workspace.id) });
  const [r] = cur ? await ctx.db.update(schema.brandKits).set({ ...b, updatedAt: new Date() }).where(eq(schema.brandKits.id, cur.id)).returning() : await ctx.db.insert(schema.brandKits).values({ workspaceId: ctx.workspace.id, ...b }).returning();
  await audit(ctx, "update", "brand_kit", r!.id, undefined, b);
  return { data: r };
} });

/* ---------------- AI ---------------- */
route({ method: "POST", path: "/ai/generate", tag: "AI", scope: "ai", summary: "Generate 3+ copy variants in English/Bangla using the brand voice (metered)", body: z.object({ kind: z.string(), brief: z.string().min(5).max(4000), language: z.enum(["en", "bn", "both"]).default("en"), variants: z.number().int().min(3).max(6).default(3), tone: z.string().optional() }), handler: async (req, ctx) => {
  const b = await body(req, z.object({ kind: z.string(), brief: z.string().min(5).max(4000), language: z.enum(["en", "bn", "both"]).default("en"), variants: z.number().int().min(3).max(6).default(3), tone: z.string().optional() }));
  const { generateContent } = await import("@/lib/ai/features");
  try { return { data: await generateContent(ctx, b) }; } catch (e) { throw aiErr(e); }
} });
route({ method: "POST", path: "/ai/ask", tag: "AI", scope: "ai", summary: "Ask your data in plain language (answer + chart rows + query + metric definition)", body: z.object({ question: z.string().min(3).max(500) }), handler: async (req, ctx) => {
  const b = await body(req, z.object({ question: z.string().min(3).max(500) }));
  const { askData } = await import("@/lib/ai/features");
  return { data: await askData(ctx, b.question) };
} });
const assistantIn = z.object({ messages: z.array(z.object({ role: z.enum(["user", "assistant"]), content: z.string().min(1).max(6000) })).min(1).max(30), page: z.string().max(200).optional(), voice: z.boolean().optional() });
route({ method: "POST", path: "/ai/assistant", tag: "AI", scope: "ai", internal: true, summary: "In-app AI assistant (text or voice): answers how-to questions and performs actions with the user's permissions", body: assistantIn, handler: async (req, ctx) => {
  const b = await body(req, assistantIn);
  if (b.voice) {
    const { hasFeature, minPlanFor, PLANS_CATALOG } = await import("@/lib/plans");
    if (!hasFeature(ctx.workspace.plan, "voice_ai")) throw new ApiError(403, "plan_upgrade_required", `Voice AI needs the ${PLANS_CATALOG[minPlanFor("voice_ai")].name} plan or higher`);
  }
  const { runAssistant } = await import("@/lib/ai/assistant");
  try { return { data: await runAssistant(ctx, b.messages, { page: b.page, voice: b.voice }) }; } catch (e) { throw aiErr(e); }
} });
route({ method: "POST", path: "/ai/assistant/confirm", tag: "AI", scope: "ai", internal: true, summary: "Confirm an action the assistant prepared (send message, move deal)", body: z.object({ token: z.string().min(20).max(4000) }), handler: async (req, ctx) => {
  const b = await body(req, z.object({ token: z.string().min(20).max(4000) }));
  const { confirmAction } = await import("@/lib/ai/assistant");
  return { data: await confirmAction(ctx, b.token) };
} });
route({ method: "POST", path: "/ai/summarize", tag: "AI", scope: "ai", summary: "Summarize a conversation and log it to the timeline", body: z.object({ conversation_id: z.string().uuid() }), handler: async (req, ctx) => {
  const b = await body(req, z.object({ conversation_id: z.string().uuid() }));
  const { summarizeConversation } = await import("@/lib/ai/features");
  try { return { data: await summarizeConversation(ctx, b.conversation_id) }; } catch (e) { throw aiErr(e); }
} });
route({ method: "POST", path: "/ai/score", tag: "AI", scope: "ai", summary: "Retrain the lead-scoring model and rescore leads", handler: async (_r, ctx) => {
  if (!can(ctx.perms, "contacts", "edit")) throw forbidden();
  const { trainScoringModel } = await import("@/lib/ai/features");
  return { data: await trainScoringModel(ctx) };
} });
route({ method: "GET", path: "/ai/recommendations", tag: "AI", scope: "ai", summary: "Budget reallocation recommendations with reasoning and expected impact", handler: async (_r, ctx) => {
  const { budgetRecommendations } = await import("@/lib/ai/features");
  return { data: await budgetRecommendations(ctx) };
} });
route({ method: "POST", path: "/ai/anomalies/run", tag: "AI", scope: "ai", internal: true, summary: "Run anomaly + pacing checks now", handler: async (_r, ctx) => {
  const { detectAnomalies, checkPacing } = await import("@/lib/ai/features");
  return { data: { anomalies: (await detectAnomalies(ctx)).length, pacing: await checkPacing(ctx) } };
} });
route({ method: "GET", path: "/ai/actions", tag: "AI", scope: "ai", summary: "Agent action approval queue", handler: async (req, ctx) => {
  const status = req.nextUrl.searchParams.get("status");
  return { data: await ctx.db.select().from(schema.aiActions).where(and(eq(schema.aiActions.workspaceId, ctx.workspace.id), status ? eq(schema.aiActions.status, status) : undefined)).orderBy(desc(schema.aiActions.createdAt)).limit(200) };
} });
route({ method: "POST", path: "/ai/actions", tag: "AI", scope: "ai", summary: "Propose an agent action from a recommendation", body: z.object({ kind: z.enum(["pause_ad", "resume_ad", "change_budget", "launch_journey"]), proposed_action: z.record(z.unknown()), reasoning: z.string(), expected_impact: z.string() }), handler: async (req, ctx) => {
  if (!can(ctx.perms, "ai_spend", "view")) throw forbidden();
  const b = await body(req, z.object({ kind: z.enum(["pause_ad", "resume_ad", "change_budget", "launch_journey"]), proposed_action: z.record(z.unknown()), reasoning: z.string(), expected_impact: z.string() }));
  const { proposeAction } = await import("@/lib/ai/features");
  return { data: await proposeAction(ctx, { agent: "budget-optimizer", kind: b.kind, proposedAction: b.proposed_action, reasoning: b.reasoning, expectedImpact: b.expected_impact }) };
} });
route({ method: "GET", path: "/ai/actions/:id/approve", tag: "AI", scope: "ai", summary: "Get an action awaiting approval", handler: async (_r, ctx, p) => {
  const a = await ctx.db.query.aiActions.findFirst({ where: and(eq(schema.aiActions.id, p.id!), eq(schema.aiActions.workspaceId, ctx.workspace.id)) });
  if (!a) throw notFound("Action");
  return { data: a };
} });
route({ method: "POST", path: "/ai/actions/:id/approve", tag: "AI", scope: "ai", summary: "Approve and execute an agent action (social replies accept an edited {text})", handler: async (req, ctx, p) => {
  const { decideAction } = await import("@/lib/ai/features");
  const b = (await req.json().catch(() => ({}))) as { text?: unknown };
  return { data: await decideAction(ctx, p.id!, "approve", typeof b.text === "string" && b.text.trim() ? { text: b.text.trim().slice(0, 2000) } : undefined) };
} });
route({ method: "POST", path: "/ai/actions/:id/reject", tag: "AI", scope: "ai", summary: "Reject an agent action", handler: async (_r, ctx, p) => {
  const { decideAction } = await import("@/lib/ai/features");
  return { data: await decideAction(ctx, p.id!, "reject") };
} });
route({ method: "GET", path: "/ai/auto-approve", tag: "AI", scope: "ai", internal: true, summary: "Auto-approve rules", handler: async (_r, ctx) => ({ data: await ctx.db.select().from(schema.aiAutoApproveRules).where(eq(schema.aiAutoApproveRules.workspaceId, ctx.workspace.id)) }) });
route({ method: "PUT", path: "/ai/auto-approve", tag: "AI", scope: "admin", internal: true, summary: "Save an auto-approve rule (admins only)", handler: async (req, ctx) => {
  if (ctx.perms.admin !== "C" || ctx.perms.ai_spend !== "A") throw forbidden("Only admins can set auto-approve rules");
  const b = await body(req, z.object({ kind: z.enum(["pause_ad", "resume_ad", "change_budget", "launch_journey"]), max_budget_change_pct: z.number().int().min(0).max(50), active: z.boolean() }));
  const cur = await ctx.db.query.aiAutoApproveRules.findFirst({ where: and(eq(schema.aiAutoApproveRules.workspaceId, ctx.workspace.id), eq(schema.aiAutoApproveRules.kind, b.kind)) });
  const vals = { maxBudgetChangePct: b.max_budget_change_pct, active: b.active, updatedAt: new Date() };
  const [r] = cur ? await ctx.db.update(schema.aiAutoApproveRules).set(vals).where(eq(schema.aiAutoApproveRules.id, cur.id)).returning() : await ctx.db.insert(schema.aiAutoApproveRules).values({ workspaceId: ctx.workspace.id, kind: b.kind, ...vals }).returning();
  await audit(ctx, "update", "ai_auto_approve", r!.id, cur, r);
  return { data: r };
} });
route({ method: "POST", path: "/ai/agent/start", tag: "AI", scope: "ai", summary: "Start the WhatsApp/Messenger qualification agent for a contact", body: z.object({ contact_id: z.string().uuid(), channel: z.enum(["whatsapp", "messenger"]).default("whatsapp") }), handler: async (req, ctx) => {
  const b = await body(req, z.object({ contact_id: z.string().uuid(), channel: z.enum(["whatsapp", "messenger"]).default("whatsapp") }));
  const { startAgent } = await import("@/lib/ai/features");
  const r = await startAgent({ ...ctx, actor: { type: "agent", id: "qualification-agent", name: "AI qualification agent" } }, b.contact_id, b.channel);
  return { data: r.message, blocked: r.blocked };
} });

function aiErr(e: unknown) {
  if (e instanceof Error && e.constructor.name === "AiUnavailable") return new ApiError(503, "ai_not_configured", e.message);
  return e;
}
