/** Admin & platform: me, notifications, workspace, users, roles, API keys, audit log, integrations, webhooks, billing, agency. */
import { z } from "zod";
import { and, desc, eq, gte, ilike, inArray, isNull, lte, or, sql, type SQL } from "drizzle-orm";
import { SignJWT } from "jose";
import { schema } from "@/db";
import { route } from "../router";
import { ApiError, body, forbidden, notFound } from "@/lib/api";
import { audit } from "@/lib/audit";
import { API_SCOPES, CAPABILITIES, DEFAULT_ROLES, can } from "@/lib/rbac";
import type { Ctx } from "@/lib/auth";
import { checkPassword, hashPassword, passwordProblem, verifyPassword } from "@/lib/auth";
import { newTotpSecret, otpauthUrl, verifyTotp } from "@/lib/crypto";
import { randomToken, sha256, period } from "@/lib/util";
import { INDUSTRIES, industryOf } from "@/lib/industry";
import { CATALOG, getConnector, syncIntegration } from "@/connectors";
import { readSecret, writeSecret, deleteSecret } from "@/lib/vault";
import { WEBHOOK_EVENTS } from "@/lib/webhooks";
import { enqueue, replayJob } from "@/lib/jobs";
import { PLANS, buildInvoiceLines, generateInvoice, usageForPeriod, aiCreditsRemaining } from "@/lib/services/billing";
import { createUser, createWorkspace, systemRole } from "@/db/seed";

const needAdmin = (ctx: Ctx) => { if (!can(ctx.perms, "admin", "edit")) throw forbidden("Admin access required"); };
const needAgency = (ctx: Ctx) => { if (!ctx.user?.isAgencyAdmin && !ctx.scopes?.includes("admin")) throw forbidden("Agency admin access required"); };
const base = () => process.env.APP_URL ?? "http://localhost:3000";

/* ---------------- me ---------------- */
route({ method: "GET", path: "/me", tag: "Admin", summary: "Current user, workspace and permissions (also used by Zapier/Make auth tests)", handler: async (_r, ctx) => ({ data: { user: ctx.user, workspace: { id: ctx.workspace.id, name: ctx.workspace.name, timezone: ctx.workspace.timezone, currency: ctx.workspace.currency, locale: ctx.workspace.locale }, role: ctx.roleName, permissions: ctx.perms, scopes: ctx.scopes ?? null } }) });
route({ method: "PATCH", path: "/me", tag: "Admin", internal: true, summary: "Update profile", handler: async (req, ctx) => {
  if (!ctx.user) throw forbidden();
  const b = await body(req, z.object({ name: z.string().min(2).optional(), phone: z.string().optional(), locale: z.enum(["en", "bn"]).optional() }));
  await ctx.db.update(schema.users).set({ ...b, updatedAt: new Date() }).where(eq(schema.users.id, ctx.user.id));
  return { data: { ok: true } };
} });
route({ method: "POST", path: "/me/password", tag: "Admin", internal: true, summary: "Change password", handler: async (req, ctx) => {
  if (!ctx.user) throw forbidden();
  const b = await body(req, z.object({ current: z.string(), next: z.string() }));
  const u = (await ctx.db.query.users.findFirst({ where: eq(schema.users.id, ctx.user.id) }))!;
  if (u.passwordHash && !(await verifyPassword(b.current, u.passwordHash))) throw new ApiError(400, "invalid_password", "Current password is incorrect");
  const pp = await checkPassword(b.next, ctx.workspace.settings?.security?.passwordMinLength);
  if (pp) throw new ApiError(422, "weak_password", pp);
  await ctx.db.update(schema.users).set({ passwordHash: await hashPassword(b.next), passwordChangedAt: new Date() }).where(eq(schema.users.id, u.id));
  await ctx.db.delete(schema.trustedDevices).where(eq(schema.trustedDevices.userId, u.id));
  await ctx.db.delete(schema.sessions).where(and(eq(schema.sessions.userId, u.id), sql`${schema.sessions.id} <> ${ctx.sessionId ?? null}`));
  await audit(ctx, "password_change", "user", u.id);
} });
route({ method: "GET", path: "/notifications", tag: "Admin", internal: true, summary: "My notifications", handler: async (req, ctx) => {
  if (!ctx.user) return { data: [], unread: 0 };
  const limit = Math.min(Number(req.nextUrl.searchParams.get("limit") ?? 30), 100);
  const mine = and(eq(schema.notifications.workspaceId, ctx.workspace.id), eq(schema.notifications.userId, ctx.user.id));
  const [rows, [u]] = await Promise.all([
    ctx.db.select().from(schema.notifications).where(mine).orderBy(desc(schema.notifications.createdAt)).limit(limit),
    ctx.db.select({ n: sql<number>`count(*)::int` }).from(schema.notifications).where(and(mine, isNull(schema.notifications.readAt))),
  ]);
  return { data: rows, unread: u?.n ?? 0 };
} });
route({ method: "POST", path: "/notifications", tag: "Admin", internal: true, summary: "Mark notifications read", handler: async (req, ctx) => {
  if (!ctx.user) return;
  const b = await body(req, z.object({ ids: z.array(z.string().uuid()).optional(), all: z.boolean().optional() }));
  const mine = and(eq(schema.notifications.workspaceId, ctx.workspace.id), eq(schema.notifications.userId, ctx.user.id));
  await ctx.db.update(schema.notifications).set({ readAt: new Date() }).where(b.all ? mine : and(mine, inArray(schema.notifications.id, b.ids?.length ? b.ids : ["00000000-0000-0000-0000-000000000000"])));
} });

/* ---------------- workspace settings (ADM-006, FLOW-007) ---------------- */
const hhmm = z.string().regex(/^\d{2}:\d{2}$/);
// Module 11 settings (SLA targets in minutes, business hours, AI autopilot, moderation lists)
const socialSettingsIn = z.object({
  sla: z.object({ dm: z.number().int().min(1).max(10080), comment: z.number().int().min(1).max(10080), review: z.number().int().min(1).max(43200) }).partial().optional(),
  hours: z.object({ days: z.array(z.number().int().min(0).max(6)), start: hhmm, end: hhmm }).optional(),
  escalation: z.enum(["notify", "reassign"]).optional(),
  featureFlags: z.object({ tiktok: z.boolean(), linkedin: z.boolean() }).partial().optional(),
  ai: z.object({ autopilot: z.boolean(), threshold: z.number().min(0.5).max(1), allowedIntents: z.array(z.string()), publicReplies: z.boolean(), languageMode: z.enum(["match", "bangla", "english"]), banglishReply: z.enum(["banglish", "bangla"]), classify: z.boolean() }).partial().optional(),
  moderation: z.object({ blockedWords: z.array(z.string().max(60)).max(500), competitorNames: z.array(z.string().max(60)).max(100) }).partial().optional(),
  whatsappNumber: z.string().max(20).optional(), spikeThreshold: z.number().int().min(3).max(1000).optional(),
});
const wsIn = z.object({
  name: z.string().min(2).optional(), timezone: z.string().optional(), currency: z.enum(["BDT", "USD", "AUD"]).optional(), locale: z.enum(["en", "bn"]).optional(),
  settings: z.object({
    quietHours: z.object({ enabled: z.boolean(), start: z.string().regex(/^\d{2}:\d{2}$/), end: z.string().regex(/^\d{2}:\d{2}$/) }).optional(),
    frequencyCap: z.object({ enabled: z.boolean(), perDay: z.number().int().min(1).max(50) }).optional(),
    mfaRequired: z.boolean().optional(), sessionTimeoutMinutes: z.number().int().min(15).max(60 * 24 * 30).optional(), brandVoice: z.string().max(2000).optional(),
    attributionModel: z.enum(["first_touch", "last_touch", "linear", "time_decay", "position_based"]).optional(), pacingThresholdPct: z.number().min(1).max(100).optional(),
    anomalyThresholdPct: z.number().min(5).max(500).optional(), dataRegion: z.string().optional(), defaultCountryCode: z.enum(["880", "61", "1"]).optional(), webhookSecret: z.string().optional(),
    social: socialSettingsIn.optional(),
    industry: z.string().refine((v) => v in INDUSTRIES, "Unknown industry").optional(), visitLabel: z.string().max(40).optional(),
  }).partial().optional(),
});
route({ method: "GET", path: "/workspace", tag: "Admin", summary: "Workspace settings", handler: async (_r, ctx) => ({ data: { ...ctx.workspace, inboundWebhookBase: `${base()}/api/v1/hooks/${ctx.workspace.hookKey}` } }) });
route({ method: "PATCH", path: "/workspace", tag: "Admin", scope: "admin", body: wsIn, summary: "Update workspace timezone, currency, language, quiet hours, caps, security", handler: async (req, ctx) => {
  needAdmin(ctx);
  const b = await body(req, wsIn);
  if (b.timezone) { try { new Intl.DateTimeFormat("en", { timeZone: b.timezone }); } catch { throw new ApiError(422, "validation_failed", "Unknown timezone"); } }
  if (b.settings?.mfaRequired && !ctx.user?.mfaEnabled) throw new ApiError(409, "enable_mfa_first", "Turn on two-factor for your own account before requiring it for everyone");
  if (b.settings?.social?.ai && ctx.perms.social_ai !== "C") throw forbidden("You need the social AI autopilot permission to change AI settings");
  const settings = { ...ctx.workspace.settings, ...(b.settings ?? {}), ...(b.settings?.social ? { social: { ...(ctx.workspace.settings?.social ?? {}), ...b.settings.social } } : {}) };
  const [r] = await ctx.db.update(schema.workspaces).set({ ...(b.name ? { name: b.name } : {}), ...(b.timezone ? { timezone: b.timezone } : {}), ...(b.currency ? { currency: b.currency } : {}), ...(b.locale ? { locale: b.locale } : {}), settings, updatedAt: new Date() }).where(eq(schema.workspaces.id, ctx.workspace.id)).returning();
  await audit(ctx, "update", "workspace", ctx.workspace.id, { timezone: ctx.workspace.timezone, currency: ctx.workspace.currency, settings: ctx.workspace.settings }, { timezone: r!.timezone, currency: r!.currency, settings: r!.settings });
  return { data: r };
} });
route({ method: "POST", path: "/workspace/industry", tag: "Admin", scope: "admin", summary: "Switch the workspace industry and apply its pack (funnel, lead fields, starter knowledge base & saved replies, SLA/AI defaults). Non-destructive: pipelines with deals are kept and a new default pipeline is added.", body: z.object({ industry: z.string(), apply_pipeline: z.boolean().default(true), add_starters: z.boolean().default(true) }), handler: async (req, ctx) => {
  needAdmin(ctx);
  const b = await body(req, z.object({ industry: z.string().refine((v) => v in INDUSTRIES, "Unknown industry"), apply_pipeline: z.boolean().default(true), add_starters: z.boolean().default(true) }));
  const { applyIndustry } = await import("@/lib/services/industry");
  const r = await applyIndustry(ctx.db, ctx.workspace.id, b.industry, { pipeline: b.apply_pipeline, starters: b.add_starters });
  await audit(ctx, "workspace.industry", "workspace", ctx.workspace.id, { industry: ctx.workspace.settings?.industry ?? null }, r);
  return { data: r };
} });
route({ method: "POST", path: "/workspace/rotate-hook-key", tag: "Admin", scope: "admin", internal: true, summary: "Rotate the inbound webhook key", handler: async (_r, ctx) => {
  needAdmin(ctx);
  const key = randomToken(16);
  await ctx.db.update(schema.workspaces).set({ hookKey: key }).where(eq(schema.workspaces.id, ctx.workspace.id));
  await audit(ctx, "rotate_hook_key", "workspace", ctx.workspace.id);
  return { data: { inboundWebhookBase: `${base()}/api/v1/hooks/${key}` } };
} });

/* ---------------- users & roles (AUTH-001) ---------------- */
route({ method: "GET", path: "/users", tag: "Admin", scope: "admin", summary: "List workspace members", handler: async (_r, ctx) => {
  if (!can(ctx.perms, "admin") && !can(ctx.perms, "pipelines")) throw forbidden();
  const rows = await ctx.db.select({ u: { id: schema.users.id, email: schema.users.email, name: schema.users.name, phone: schema.users.phone, status: schema.users.status, mfaEnabled: schema.users.mfaEnabled, lastLoginAt: schema.users.lastLoginAt }, m: schema.memberships, role: { id: schema.roles.id, key: schema.roles.key, name: schema.roles.name } })
    .from(schema.memberships).innerJoin(schema.users, eq(schema.users.id, schema.memberships.userId)).innerJoin(schema.roles, eq(schema.roles.id, schema.memberships.roleId)).where(eq(schema.memberships.workspaceId, ctx.workspace.id));
  return { data: rows.map(({ u, m, role }) => ({ ...u, membershipId: m.id, active: m.active, territory: m.territory, projects: m.projects, role })) };
} });
async function inviteLink(userId: string, workspaceId: string) {
  const token = await new SignJWT({ uid: userId, ws: workspaceId }).setProtectedHeader({ alg: "HS256" }).setExpirationTime("7d").sign(new TextEncoder().encode(process.env.AUTH_SECRET ?? "tempest-pulse-dev-secret-change-me"));
  return `${base()}/invite/${token}`;
}
route({ method: "POST", path: "/users", tag: "Admin", scope: "admin", summary: "Invite a user to the workspace (returns an invite link; emailed when an email provider is connected)", body: z.object({ email: z.string().email(), name: z.string().min(1), role_id: z.string().uuid(), territory: z.string().optional(), projects: z.array(z.string()).optional() }), handler: async (req, ctx) => {
  needAdmin(ctx);
  const b = await body(req, z.object({ email: z.string().email(), name: z.string().min(1), role_id: z.string().uuid(), territory: z.string().optional(), projects: z.array(z.string()).optional() }));
  const role = await ctx.db.query.roles.findFirst({ where: and(eq(schema.roles.id, b.role_id), or(isNull(schema.roles.workspaceId), eq(schema.roles.workspaceId, ctx.workspace.id))) });
  if (!role) throw notFound("Role");
  if (role.key === "agency_admin" && !ctx.user?.isAgencyAdmin) throw forbidden("Only agency admins can grant agency admin");
  let user = await ctx.db.query.users.findFirst({ where: eq(schema.users.email, b.email.toLowerCase()) });
  if (!user) user = await createUser(ctx.db, { email: b.email, name: b.name, status: "invited", agencyId: ctx.workspace.agencyId });
  const exists = await ctx.db.query.memberships.findFirst({ where: and(eq(schema.memberships.workspaceId, ctx.workspace.id), eq(schema.memberships.userId, user.id)) });
  if (exists) await ctx.db.update(schema.memberships).set({ roleId: role.id, active: true, territory: b.territory ?? null, projects: b.projects ?? [] }).where(eq(schema.memberships.id, exists.id));
  else await ctx.db.insert(schema.memberships).values({ workspaceId: ctx.workspace.id, userId: user.id, roleId: role.id, territory: b.territory ?? null, projects: b.projects ?? [] });
  const link = user.status === "invited" ? await inviteLink(user.id, ctx.workspace.id) : null;
  let emailed = false;
  if (link) {
    const { findIntegrations, pushVia } = await import("@/connectors");
    const [email] = await findIntegrations(ctx, ["ses", "sendgrid"]);
    if (email) { try { await pushVia(ctx, email, "send", { to: user.email, subject: `You're invited to ${ctx.workspace.name}`, messageId: `invite-${user.id}`, html: `<p>Hi ${b.name},</p><p>${ctx.user?.name ?? "Your admin"} invited you to <b>${ctx.workspace.name}</b>.</p><p><a href="${link}">Accept invitation</a> (valid 7 days)</p>` }); emailed = true; } catch { /* link still returned */ } }
  }
  await audit(ctx, "invite", "user", user.id, undefined, { email: user.email, role: role.key });
  return { data: { userId: user.id, inviteLink: link, emailed } };
} });
route({ method: "PATCH", path: "/users/:id", tag: "Admin", scope: "admin", summary: "Change a member's role, territory, projects or deactivate", body: z.object({ role_id: z.string().uuid().optional(), active: z.boolean().optional(), territory: z.string().nullable().optional(), projects: z.array(z.string()).optional(), team: z.string().max(60).nullable().optional(), availability: z.enum(["online", "away"]).optional(), social_account_ids: z.array(z.string().uuid()).optional() }), handler: async (req, ctx, p) => {
  needAdmin(ctx);
  const b = await body(req, z.object({ role_id: z.string().uuid().optional(), active: z.boolean().optional(), territory: z.string().nullable().optional(), projects: z.array(z.string()).optional(), team: z.string().max(60).nullable().optional(), availability: z.enum(["online", "away"]).optional(), social_account_ids: z.array(z.string().uuid()).optional() }));
  const m = await ctx.db.query.memberships.findFirst({ where: and(eq(schema.memberships.workspaceId, ctx.workspace.id), eq(schema.memberships.userId, p.id!)) });
  if (!m) throw notFound("Member");
  if (p.id === ctx.user?.id && b.active === false) throw new ApiError(409, "conflict", "You cannot deactivate yourself");
  const [r] = await ctx.db.update(schema.memberships).set({ ...(b.role_id ? { roleId: b.role_id } : {}), ...(b.active !== undefined ? { active: b.active } : {}), ...(b.territory !== undefined ? { territory: b.territory } : {}), ...(b.projects ? { projects: b.projects } : {}), ...(b.team !== undefined ? { team: b.team } : {}), ...(b.availability ? { availability: b.availability } : {}), ...(b.social_account_ids ? { socialAccountIds: b.social_account_ids } : {}), updatedAt: new Date() }).where(eq(schema.memberships.id, m.id)).returning();
  if (b.active === false) await ctx.db.delete(schema.sessions).where(and(eq(schema.sessions.userId, p.id!), eq(schema.sessions.workspaceId, ctx.workspace.id)));
  await audit(ctx, "update", "membership", m.id, m, r);
  return { data: r };
} });
route({ method: "POST", path: "/users/:id/invite-link", tag: "Admin", scope: "admin", internal: true, summary: "Regenerate invite link", handler: async (_r, ctx, p) => { needAdmin(ctx); return { data: { inviteLink: await inviteLink(p.id!, ctx.workspace.id) } }; } });

route({ method: "GET", path: "/roles", tag: "Admin", summary: "Roles and the permission matrix", handler: async (_r, ctx) => ({ data: await ctx.db.select().from(schema.roles).where(or(isNull(schema.roles.workspaceId), eq(schema.roles.workspaceId, ctx.workspace.id))), capabilities: CAPABILITIES }) });
const roleIn = z.object({ name: z.string().min(2), clone_from: z.string().optional(), permissions: z.record(z.enum(["C", "V", "A", "C:assigned", "V:own", ""])).optional() });
route({ method: "POST", path: "/roles", tag: "Admin", scope: "admin", body: roleIn, summary: "Create a custom role (cloned from a default)", handler: async (req, ctx) => {
  needAdmin(ctx);
  const b = await body(req, roleIn);
  const src = DEFAULT_ROLES.find((r) => r.key === b.clone_from) ?? DEFAULT_ROLES[2]!;
  const perms = { ...src.permissions, ...(b.permissions ?? {}) };
  if (!ctx.user?.isAgencyAdmin) perms.agency = "";
  const [r] = await ctx.db.insert(schema.roles).values({ workspaceId: ctx.workspace.id, key: `custom_${randomToken(4).toLowerCase()}`, name: b.name, permissions: perms, isSystem: false }).returning();
  await audit(ctx, "create", "role", r!.id, undefined, r);
  return { data: r };
} });
route({ method: "PATCH", path: "/roles/:id", tag: "Admin", scope: "admin", body: roleIn.partial(), summary: "Edit a custom role", handler: async (req, ctx, p) => {
  needAdmin(ctx);
  const cur = await ctx.db.query.roles.findFirst({ where: and(eq(schema.roles.id, p.id!), eq(schema.roles.workspaceId, ctx.workspace.id)) });
  if (!cur) throw new ApiError(409, "conflict", "Default roles can’t be edited — clone one instead");
  const b = await body(req, roleIn.partial());
  const perms = { ...cur.permissions, ...(b.permissions ?? {}) };
  if (!ctx.user?.isAgencyAdmin) perms.agency = "";
  const [r] = await ctx.db.update(schema.roles).set({ ...(b.name ? { name: b.name } : {}), permissions: perms, updatedAt: new Date() }).where(eq(schema.roles.id, cur.id)).returning();
  await audit(ctx, "update", "role", cur.id, cur, r);
  return { data: r };
} });
route({ method: "DELETE", path: "/roles/:id", tag: "Admin", scope: "admin", summary: "Delete a custom role (must be unused)", handler: async (_r, ctx, p) => {
  needAdmin(ctx);
  const inUse = await ctx.db.query.memberships.findFirst({ where: eq(schema.memberships.roleId, p.id!) });
  if (inUse) throw new ApiError(409, "conflict", "Role is assigned to members");
  await ctx.db.delete(schema.roles).where(and(eq(schema.roles.id, p.id!), eq(schema.roles.workspaceId, ctx.workspace.id)));
  await audit(ctx, "delete", "role", p.id!);
} });

/* ---------------- API keys (ADM-007) ---------------- */
route({ method: "GET", path: "/api-keys", tag: "Admin", scope: "admin", summary: "List API keys", handler: async (_r, ctx) => {
  needAdmin(ctx);
  const rows = await ctx.db.select({ id: schema.apiKeys.id, name: schema.apiKeys.name, prefix: schema.apiKeys.prefix, scopes: schema.apiKeys.scopes, lastUsedAt: schema.apiKeys.lastUsedAt, revokedAt: schema.apiKeys.revokedAt, createdAt: schema.apiKeys.createdAt }).from(schema.apiKeys).where(eq(schema.apiKeys.workspaceId, ctx.workspace.id)).orderBy(desc(schema.apiKeys.createdAt));
  return { data: rows, scopes: API_SCOPES };
} });
route({ method: "POST", path: "/api-keys", tag: "Admin", scope: "admin", summary: "Create a scoped API key (shown once)", body: z.object({ name: z.string().min(1), scopes: z.array(z.enum(API_SCOPES)).min(1) }), handler: async (req, ctx) => {
  needAdmin(ctx);
  const b = await body(req, z.object({ name: z.string().min(1), scopes: z.array(z.enum(API_SCOPES)).min(1) }));
  if (ctx.scopes && b.scopes.includes("admin") && !ctx.scopes.includes("admin")) throw forbidden();
  const raw = `tp_${process.env.NODE_ENV === "production" ? "live" : "test"}_${randomToken(28)}`;
  const [r] = await ctx.db.insert(schema.apiKeys).values({ workspaceId: ctx.workspace.id, name: b.name, prefix: raw.slice(0, 12), hashedKey: sha256(raw), scopes: b.scopes, createdBy: ctx.user?.id ?? null }).returning();
  await audit(ctx, "create", "api_key", r!.id, undefined, { name: b.name, scopes: b.scopes });
  return { data: { id: r!.id, key: raw, name: r!.name, scopes: r!.scopes } };
} });
route({ method: "DELETE", path: "/api-keys/:id", tag: "Admin", scope: "admin", summary: "Revoke an API key", handler: async (_r, ctx, p) => {
  needAdmin(ctx);
  await ctx.db.update(schema.apiKeys).set({ revokedAt: new Date() }).where(and(eq(schema.apiKeys.id, p.id!), eq(schema.apiKeys.workspaceId, ctx.workspace.id)));
  await audit(ctx, "revoke", "api_key", p.id!);
} });

/* ---------------- audit log (ADM-003) ---------------- */
route({ method: "GET", path: "/audit-logs", tag: "Admin", scope: "admin", summary: "Search the audit log (?user=&object=&action=&from=&to=&q=)", handler: async (req, ctx) => {
  if (!can(ctx.perms, "admin")) throw forbidden();
  const sp = req.nextUrl.searchParams;
  const conds: (SQL | undefined)[] = [eq(schema.auditLogs.workspaceId, ctx.workspace.id)];
  if (sp.get("user")) conds.push(eq(schema.auditLogs.actorId, sp.get("user")!));
  if (sp.get("object")) conds.push(eq(schema.auditLogs.objectType, sp.get("object")!));
  if (sp.get("object_id")) conds.push(eq(schema.auditLogs.objectId, sp.get("object_id")!));
  if (sp.get("action")) conds.push(ilike(schema.auditLogs.action, `%${sp.get("action")}%`));
  if (sp.get("from")) conds.push(gte(schema.auditLogs.at, new Date(sp.get("from")!)));
  if (sp.get("to")) conds.push(lte(schema.auditLogs.at, new Date(`${sp.get("to")}T23:59:59Z`)));
  if (sp.get("q")) conds.push(or(ilike(schema.auditLogs.actorName, `%${sp.get("q")}%`), ilike(schema.auditLogs.action, `%${sp.get("q")}%`), ilike(schema.auditLogs.objectType, `%${sp.get("q")}%`)));
  const rows = await ctx.db.select().from(schema.auditLogs).where(and(...conds)).orderBy(desc(schema.auditLogs.at)).limit(Math.min(Number(sp.get("limit") ?? 200), 1000));
  return { data: rows };
} });

/* ---------------- integrations hub (INT-001/002/005) ---------------- */
route({ method: "GET", path: "/integrations", tag: "Integrations", scope: "admin", summary: "Catalog + connected integrations with health", handler: async (_r, ctx) => {
  if (!can(ctx.perms, "admin")) throw forbidden();
  const rows = await ctx.db.select().from(schema.integrations).where(eq(schema.integrations.workspaceId, ctx.workspace.id)).orderBy(desc(schema.integrations.createdAt));
  const errs = await ctx.db.select({ i: schema.integrationLogs.integrationId, n: sql<number>`count(*) FILTER (WHERE status = 'error')::int`, t: sql<number>`count(*)::int` }).from(schema.integrationLogs).where(and(eq(schema.integrationLogs.workspaceId, ctx.workspace.id), gte(schema.integrationLogs.at, new Date(Date.now() - 7 * 86400000)))).groupBy(schema.integrationLogs.integrationId);
  const oauthReady = { meta: !!process.env.META_APP_ID, google: !!process.env.GOOGLE_CLIENT_ID };
  return {
    data: rows.map(({ tokenRef: _t, ...i }) => ({ ...i, errors7d: errs.find((e) => e.i === i.id)?.n ?? 0, calls7d: errs.find((e) => e.i === i.id)?.t ?? 0, config: { ...i.config, data: undefined } })),
    catalog: CATALOG, oauthReady, webhookBase: `${base()}/api/v1/hooks/${ctx.workspace.hookKey}`,
  };
} });
const connectIn = z.object({ provider: z.string(), mode: z.enum(["live", "sandbox"]), credentials: z.record(z.string()).default({}), config: z.record(z.unknown()).default({}) });
route({ method: "POST", path: "/integrations", tag: "Integrations", scope: "admin", body: connectIn, summary: "Connect a provider with credentials (or in sandbox mode)", handler: async (req, ctx) => {
  needAdmin(ctx);
  const b = await body(req, connectIn);
  const c = getConnector(b.provider);
  if (!c) throw notFound("Provider");
  const secretFields = new Set((c.meta.fields ?? []).filter((f) => f.secret).map((f) => f.key));
  const creds: Record<string, string> = { ...b.credentials };
  const config: Record<string, unknown> = { ...b.config };
  for (const [k, v] of Object.entries(b.credentials)) if (!secretFields.has(k) && k !== "accessToken") { config[k] = v; }
  for (const f of c.meta.fields ?? []) if (!f.optional && !f.secret && b.mode === "live" && !config[f.key] && c.meta.auth === "credentials") throw new ApiError(422, "validation_failed", `${f.label} is required`);
  let accountRef = String(config.adAccountId ?? config.customerId ?? config.advertiserId ?? config.phoneNumberId ?? config.propertyId ?? config.siteUrl ?? config.fromEmail ?? config.senderId ?? config.storeId ?? config.accountSid ?? b.provider);
  let displayName = `${c.meta.name}${b.mode === "sandbox" ? " (sandbox)" : ""}`;
  let expiresAt: Date | null = null;
  if (b.mode === "live" && c.connect) {
    try {
      const r = await c.connect(ctx, creds, config);
      accountRef = r.accountRef; displayName = r.displayName; expiresAt = r.expiresAt ?? null;
      Object.assign(config, r.config ?? {});
    } catch (e) { throw new ApiError(400, "connect_failed", `Could not connect: ${(e as Error).message}`); }
  }
  const existing = await ctx.db.query.integrations.findFirst({ where: and(eq(schema.integrations.workspaceId, ctx.workspace.id), eq(schema.integrations.provider, b.provider)) });
  const tokenRef = await writeSecret(ctx.db, ctx.workspace.id, b.mode === "sandbox" ? { sandbox: "true" } : creds, existing?.tokenRef);
  const vals = { workspaceId: ctx.workspace.id, provider: b.provider, accountRef, displayName, config, tokenRef, mode: b.mode, status: "connected", lastError: null, expiresAt, scopes: c.meta.scopes ?? [], updatedAt: new Date() };
  const [r] = existing ? await ctx.db.update(schema.integrations).set(vals).where(eq(schema.integrations.id, existing.id)).returning() : await ctx.db.insert(schema.integrations).values({ ...vals, createdBy: ctx.user?.id ?? null }).returning();
  await audit(ctx, "connect", "integration", r!.id, undefined, { provider: b.provider, mode: b.mode });
  if (c.sync) await enqueue(ctx.db, "integration.sync", { workspaceId: ctx.workspace.id, integrationId: r!.id }, { workspaceId: ctx.workspace.id });
  const { tokenRef: _t, ...safe } = r!;
  return { data: safe };
} });
route({ method: "PATCH", path: "/integrations/:id", tag: "Integrations", scope: "admin", summary: "Update integration config or field mapping (INT-005)", body: z.object({ config: z.record(z.unknown()).optional(), field_mapping: z.record(z.string()).optional() }), handler: async (req, ctx, p) => {
  needAdmin(ctx);
  const b = await body(req, z.object({ config: z.record(z.unknown()).optional(), field_mapping: z.record(z.string()).optional() }));
  const cur = await ctx.db.query.integrations.findFirst({ where: and(eq(schema.integrations.id, p.id!), eq(schema.integrations.workspaceId, ctx.workspace.id)) });
  if (!cur) throw notFound("Integration");
  const [r] = await ctx.db.update(schema.integrations).set({ ...(b.config ? { config: { ...cur.config, ...b.config } } : {}), ...(b.field_mapping ? { fieldMapping: b.field_mapping } : {}), updatedAt: new Date() }).where(eq(schema.integrations.id, cur.id)).returning();
  await audit(ctx, "update", "integration", cur.id, { config: cur.config, mapping: cur.fieldMapping }, { config: r!.config, mapping: r!.fieldMapping });
  const { tokenRef: _t, ...safe } = r!;
  return { data: safe };
} });
route({ method: "DELETE", path: "/integrations/:id", tag: "Integrations", scope: "admin", summary: "Disconnect an integration (credentials are deleted from the vault)", handler: async (_r, ctx, p) => {
  needAdmin(ctx);
  const cur = await ctx.db.query.integrations.findFirst({ where: and(eq(schema.integrations.id, p.id!), eq(schema.integrations.workspaceId, ctx.workspace.id)) });
  if (!cur) throw notFound("Integration");
  if (cur.tokenRef) await deleteSecret(ctx.db, cur.tokenRef);
  await ctx.db.delete(schema.integrations).where(eq(schema.integrations.id, cur.id));
  await audit(ctx, "disconnect", "integration", cur.id, { provider: cur.provider });
} });
route({ method: "POST", path: "/integrations/:id/sync", tag: "Integrations", scope: "admin", summary: "Run a sync now / retry a failed sync", handler: async (_r, ctx, p) => {
  if (!can(ctx.perms, "admin")) throw forbidden();
  const cur = await ctx.db.query.integrations.findFirst({ where: and(eq(schema.integrations.id, p.id!), eq(schema.integrations.workspaceId, ctx.workspace.id)) });
  if (!cur) throw notFound("Integration");
  try { return { data: await syncIntegration(ctx, cur) }; } catch (e) { throw new ApiError(502, "sync_failed", (e as Error).message); }
} });
route({ method: "GET", path: "/integrations/:id/logs", tag: "Integrations", scope: "admin", summary: "Connection health log", handler: async (_r, ctx, p) => {
  if (!can(ctx.perms, "admin")) throw forbidden();
  return { data: await ctx.db.select().from(schema.integrationLogs).where(and(eq(schema.integrationLogs.workspaceId, ctx.workspace.id), eq(schema.integrationLogs.integrationId, p.id!))).orderBy(desc(schema.integrationLogs.at)).limit(200) };
} });
route({ method: "GET", path: "/integrations/:id/sample", tag: "Integrations", scope: "admin", internal: true, summary: "Sample provider fields for mapping", handler: async (_r, ctx, p) => {
  const cur = await ctx.db.query.integrations.findFirst({ where: and(eq(schema.integrations.id, p.id!), eq(schema.integrations.workspaceId, ctx.workspace.id)) });
  if (!cur) throw notFound("Integration");
  const samples: Record<string, string[]> = { meta: industryOf(ctx.workspace.settings).leadFormFields, google_ads: ["FULL_NAME", "EMAIL", "PHONE_NUMBER", "CITY", "budget"], tiktok: ["name", "email", "phone_number"], linkedin: ["firstName", "lastName", "emailAddress", "phoneNumber", "company"] };
  return { data: samples[cur.provider] ?? [] };
} });
/** OAuth 2.0 connect flow (Meta, Google). Tokens land in the vault; the integration is created in live mode. */
route({ method: "GET", path: "/integrations/oauth/:provider/start", tag: "Integrations", scope: "admin", internal: true, summary: "Start OAuth", handler: async (req, ctx, p) => {
  needAdmin(ctx);
  const state = await new SignJWT({ ws: ctx.workspace.id, provider: p.provider, u: ctx.user?.id }).setProtectedHeader({ alg: "HS256" }).setExpirationTime("15m").sign(new TextEncoder().encode(process.env.AUTH_SECRET ?? "tempest-pulse-dev-secret-change-me"));
  const redirect = `${base()}/api/v1/integrations/oauth/callback`;
  const c = getConnector(p.provider!);
  if (!c) throw notFound("Provider");
  let url: string;
  if (c.meta.oauthProvider === "meta") {
    if (!process.env.META_APP_ID) throw new ApiError(409, "not_configured", "Set META_APP_ID and META_APP_SECRET to enable Meta OAuth");
    url = `https://www.facebook.com/${process.env.META_GRAPH_VERSION ?? "v21.0"}/dialog/oauth?${new URLSearchParams({ client_id: process.env.META_APP_ID, redirect_uri: redirect, state, scope: (c.meta.scopes ?? []).join(","), response_type: "code" })}`;
  } else if (c.meta.oauthProvider === "google") {
    if (!process.env.GOOGLE_CLIENT_ID) throw new ApiError(409, "not_configured", "Set GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET to enable Google OAuth");
    url = `https://accounts.google.com/o/oauth2/v2/auth?${new URLSearchParams({ client_id: process.env.GOOGLE_CLIENT_ID, redirect_uri: redirect, state, scope: (c.meta.scopes ?? []).join(" "), response_type: "code", access_type: "offline", prompt: "consent" })}`;
  } else throw new ApiError(422, "unsupported", "This provider connects with credentials");
  const params = new URLSearchParams(req.nextUrl.search);
  return Response.redirect(url + (params.size ? "" : ""), 302);
} });
route({ method: "GET", path: "/integrations/oauth/callback", tag: "Integrations", internal: true, summary: "OAuth callback", handler: async (req, ctx) => {
  const { jwtVerify } = await import("jose");
  const back = (msg: string, ok = false) => Response.redirect(`${base()}/integrations?${ok ? "connected" : "error"}=${encodeURIComponent(msg)}`, 302);
  try {
    const { payload } = await jwtVerify(req.nextUrl.searchParams.get("state") ?? "", new TextEncoder().encode(process.env.AUTH_SECRET ?? "tempest-pulse-dev-secret-change-me"));
    if (payload.ws !== ctx.workspace.id) return back("Workspace changed during sign-in");
    const provider = String(payload.provider);
    const code = req.nextUrl.searchParams.get("code");
    if (!code) return back(req.nextUrl.searchParams.get("error_description") ?? "Authorization cancelled");
    const redirect = `${base()}/api/v1/integrations/oauth/callback`;
    const c = getConnector(provider)!;
    let creds: Record<string, string>;
    let expiresAt: Date | null = null;
    if (c.meta.oauthProvider === "meta") {
      const short = await fetch(`https://graph.facebook.com/${process.env.META_GRAPH_VERSION ?? "v21.0"}/oauth/access_token?${new URLSearchParams({ client_id: process.env.META_APP_ID ?? "", client_secret: process.env.META_APP_SECRET ?? "", redirect_uri: redirect, code })}`).then((r) => r.json());
      if (!short.access_token) return back(short.error?.message ?? "Meta token exchange failed");
      const long = await fetch(`https://graph.facebook.com/${process.env.META_GRAPH_VERSION ?? "v21.0"}/oauth/access_token?grant_type=fb_exchange_token&client_id=${process.env.META_APP_ID}&client_secret=${process.env.META_APP_SECRET}&fb_exchange_token=${short.access_token}`).then((r) => r.json());
      creds = { accessToken: long.access_token ?? short.access_token };
      expiresAt = long.expires_in ? new Date(Date.now() + long.expires_in * 1000) : new Date(Date.now() + 60 * 86400000);
    } else {
      const t = await fetch("https://oauth2.googleapis.com/token", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ code, client_id: process.env.GOOGLE_CLIENT_ID ?? "", client_secret: process.env.GOOGLE_CLIENT_SECRET ?? "", redirect_uri: redirect, grant_type: "authorization_code" }) }).then((r) => r.json());
      if (!t.access_token) return back(t.error_description ?? "Google token exchange failed");
      creds = { accessToken: t.access_token, refreshToken: t.refresh_token, expiresAt: String(Date.now() + t.expires_in * 1000) };
    }
    const existing = await ctx.db.query.integrations.findFirst({ where: and(eq(schema.integrations.workspaceId, ctx.workspace.id), eq(schema.integrations.provider, provider)) });
    const tokenRef = await writeSecret(ctx.db, ctx.workspace.id, creds, existing?.mode === "live" ? existing.tokenRef : null);
    let displayName = c.meta.name;
    if (c.connect) { try { displayName = (await c.connect(ctx, creds, existing?.config ?? {})).displayName; } catch { /* account selection happens in settings */ } }
    const vals = { mode: "live", status: "connected", tokenRef, expiresAt, displayName, lastError: null, scopes: c.meta.scopes ?? [], updatedAt: new Date() };
    if (existing) await ctx.db.update(schema.integrations).set(vals).where(eq(schema.integrations.id, existing.id));
    else await ctx.db.insert(schema.integrations).values({ workspaceId: ctx.workspace.id, provider, accountRef: provider, config: {}, ...vals, createdBy: ctx.user?.id ?? null });
    await audit(ctx, "connect", "integration", existing?.id ?? null, undefined, { provider, mode: "live", via: "oauth" });
    return back(`${c.meta.name} connected — choose the account in its settings`, true);
  } catch (e) {
    return back((e as Error).message);
  }
} });

/* ---------------- outbound webhooks (INT-004) ---------------- */
route({ method: "GET", path: "/webhooks", tag: "Webhooks", scope: "read:webhooks", summary: "List webhook subscriptions", handler: async (_r, ctx) => ({ data: (await ctx.db.select().from(schema.webhookSubscriptions).where(eq(schema.webhookSubscriptions.workspaceId, ctx.workspace.id))).map((s) => ({ ...s, secret: `${s.secret.slice(0, 6)}…` })), events: WEBHOOK_EVENTS }) });
route({ method: "POST", path: "/webhooks", tag: "Webhooks", scope: "write:webhooks", summary: "Subscribe a URL to events (secret returned once)", body: z.object({ url: z.string().url(), events: z.array(z.string()).min(1) }), handler: async (req, ctx) => {
  const b = await body(req, z.object({ url: z.string().url(), events: z.array(z.string()).min(1) }));
  const bad = b.events.filter((e) => e !== "*" && !(WEBHOOK_EVENTS as readonly string[]).includes(e));
  if (bad.length) throw new ApiError(422, "validation_failed", `Unknown events: ${bad.join(", ")}`);
  if (process.env.NODE_ENV === "production" && !b.url.startsWith("https://")) throw new ApiError(422, "validation_failed", "Webhook URLs must use https");
  const secret = `whsec_${randomToken(24)}`;
  const [r] = await ctx.db.insert(schema.webhookSubscriptions).values({ workspaceId: ctx.workspace.id, url: b.url, events: b.events, secret, createdBy: ctx.user?.id ?? null }).returning();
  await audit(ctx, "create", "webhook", r!.id, undefined, { url: b.url, events: b.events });
  return { data: r };
} });
route({ method: "DELETE", path: "/webhooks/:id", tag: "Webhooks", scope: "write:webhooks", summary: "Delete a subscription (Zapier/Make unsubscribe)", handler: async (_r, ctx, p) => {
  await ctx.db.delete(schema.webhookSubscriptions).where(and(eq(schema.webhookSubscriptions.id, p.id!), eq(schema.webhookSubscriptions.workspaceId, ctx.workspace.id)));
  await audit(ctx, "delete", "webhook", p.id!);
} });
route({ method: "POST", path: "/webhooks/:id/test", tag: "Webhooks", scope: "write:webhooks", internal: true, summary: "Send a test event", handler: async (_r, ctx, p) => {
  const s = await ctx.db.query.webhookSubscriptions.findFirst({ where: and(eq(schema.webhookSubscriptions.id, p.id!), eq(schema.webhookSubscriptions.workspaceId, ctx.workspace.id)) });
  if (!s) throw notFound("Webhook");
  const eventId = crypto.randomUUID();
  const [d] = await ctx.db.insert(schema.webhookDeliveries).values({ workspaceId: ctx.workspace.id, subscriptionId: s.id, eventId, eventType: "test.ping", payload: { id: eventId, type: "test.ping", workspace_id: ctx.workspace.id, occurred_at: new Date().toISOString(), data: { hello: "world" } } }).returning();
  const { deliverWebhook } = await import("@/lib/webhooks");
  try { await deliverWebhook(ctx.db, d!.id); } catch { /* status recorded */ }
  return { data: await ctx.db.query.webhookDeliveries.findFirst({ where: eq(schema.webhookDeliveries.id, d!.id) }) };
} });
route({ method: "GET", path: "/webhooks/deliveries", tag: "Webhooks", scope: "read:webhooks", summary: "Recent deliveries", handler: async (_r, ctx) => ({ data: await ctx.db.select().from(schema.webhookDeliveries).where(eq(schema.webhookDeliveries.workspaceId, ctx.workspace.id)).orderBy(desc(schema.webhookDeliveries.createdAt)).limit(200) }) });
route({ method: "POST", path: "/webhooks/deliveries/:id/replay", tag: "Webhooks", scope: "write:webhooks", summary: "Replay a delivery", handler: async (_r, ctx, p) => {
  const d = await ctx.db.query.webhookDeliveries.findFirst({ where: and(eq(schema.webhookDeliveries.id, p.id!), eq(schema.webhookDeliveries.workspaceId, ctx.workspace.id)) });
  if (!d) throw notFound("Delivery");
  await ctx.db.update(schema.webhookDeliveries).set({ status: "pending", createdAt: new Date() }).where(eq(schema.webhookDeliveries.id, d.id));
  await enqueue(ctx.db, "webhook.deliver", { deliveryId: d.id, workspaceId: ctx.workspace.id }, { workspaceId: ctx.workspace.id });
} });

/* ---------------- jobs / dead-letter queue (NFR-008) ---------------- */
route({ method: "GET", path: "/jobs", tag: "Admin", scope: "admin", internal: true, summary: "Background jobs (?status=dead)", handler: async (req, ctx) => {
  needAdmin(ctx);
  const st = req.nextUrl.searchParams.get("status");
  return { data: await ctx.db.select().from(schema.jobs).where(and(eq(schema.jobs.workspaceId, ctx.workspace.id), st ? eq(schema.jobs.status, st) : undefined)).orderBy(desc(schema.jobs.updatedAt)).limit(200) };
} });
route({ method: "POST", path: "/jobs/:id/replay", tag: "Admin", scope: "admin", internal: true, summary: "Replay a dead-lettered job", handler: async (_r, ctx, p) => {
  needAdmin(ctx);
  const j = await ctx.db.query.jobs.findFirst({ where: and(eq(schema.jobs.id, p.id!), eq(schema.jobs.workspaceId, ctx.workspace.id)) });
  if (!j) throw notFound("Job");
  await replayJob(ctx.db, j.id);
} });

/* ---------------- billing (ADM-004) ---------------- */
route({ method: "GET", path: "/billing", tag: "Billing", scope: "admin", summary: "Plan, usage meters and invoices", handler: async (_r, ctx) => {
  if (!can(ctx.perms, "admin")) throw forbidden();
  const usage = await usageForPeriod(ctx);
  const projected = buildInvoiceLines(ctx.workspace.plan, ctx.workspace.currency, usage);
  const invoices = await ctx.db.select().from(schema.invoices).where(eq(schema.invoices.workspaceId, ctx.workspace.id)).orderBy(desc(schema.invoices.createdAt));
  const { PLANS_CATALOG, normalizePlan, subscriptionAccess } = await import("@/lib/plans");
  const { paymentsConfigured } = await import("@/lib/services/subscription");
  const w = ctx.workspace;
  return { data: { plan: w.plan, plans: PLANS, usage, period: period(), projected, invoices, credits: await aiCreditsRemaining(ctx),
    subscription: { plan: normalizePlan(w.plan), status: w.subscriptionStatus, trialEndsAt: w.trialEndsAt, currentPeriodEnd: w.currentPeriodEnd, hasCustomer: !!w.billingCustomerId, access: subscriptionAccess(w), paymentsConfigured: paymentsConfigured() || process.env.NODE_ENV !== "production" },
    catalog: PLANS_CATALOG } };
} });
route({ method: "POST", path: "/billing/checkout", tag: "Billing", scope: "admin", summary: "Start a subscription checkout (Stripe) for Starter, Growth or Enterprise — or change plan on an active subscription", body: z.object({ plan: z.enum(["starter", "growth", "enterprise"]) }), handler: async (req, ctx) => {
  needAdmin(ctx);
  const b = await body(req, z.object({ plan: z.enum(["starter", "growth", "enterprise"]) }));
  const { checkoutUrl } = await import("@/lib/services/subscription");
  return { data: await checkoutUrl(ctx, b.plan, process.env.APP_URL ?? req.nextUrl.origin) };
} });
route({ method: "POST", path: "/billing/confirm", tag: "Billing", scope: "admin", internal: true, summary: "Confirm a completed Stripe checkout", body: z.object({ session_id: z.string().min(5).max(200) }), handler: async (req, ctx) => {
  needAdmin(ctx);
  const b = await body(req, z.object({ session_id: z.string().min(5).max(200) }));
  const { confirmCheckout } = await import("@/lib/services/subscription");
  return { data: await confirmCheckout(ctx, b.session_id) };
} });
route({ method: "POST", path: "/billing/portal", tag: "Billing", scope: "admin", summary: "Open the Stripe customer portal (payment method, invoices, cancel)", handler: async (req, ctx) => {
  needAdmin(ctx);
  const { portalUrl } = await import("@/lib/services/subscription");
  return { data: await portalUrl(ctx, process.env.APP_URL ?? req.nextUrl.origin) };
} });
route({ method: "POST", path: "/billing/plan", tag: "Billing", scope: "admin", summary: "Change plan", body: z.object({ plan: z.enum(["starter", "growth", "enterprise", "agency"]) }), handler: async (req, ctx) => {
  needAgency(ctx);
  const b = await body(req, z.object({ plan: z.enum(["starter", "growth", "enterprise", "agency"]) }));
  await ctx.db.update(schema.workspaces).set({ plan: b.plan }).where(eq(schema.workspaces.id, ctx.workspace.id));
  await audit(ctx, "plan_change", "workspace", ctx.workspace.id, { plan: ctx.workspace.plan }, { plan: b.plan });
} });
route({ method: "POST", path: "/billing/invoices/close", tag: "Billing", scope: "admin", internal: true, summary: "Close a period into an invoice", body: z.object({ period: z.string().regex(/^\d{4}-\d{2}$/) }), handler: async (req, ctx) => {
  needAgency(ctx);
  const b = await body(req, z.object({ period: z.string().regex(/^\d{4}-\d{2}$/) }));
  return { data: await generateInvoice(ctx, b.period) };
} });
route({ method: "POST", path: "/billing/invoices/:id/pay", tag: "Billing", scope: "admin", summary: "Get a checkout link (Stripe for USD/AUD, SSLCommerz or bKash for BDT)", body: z.object({ provider: z.enum(["stripe", "sslcommerz", "bkash"]).optional() }), handler: async (req, ctx, p) => {
  if (!can(ctx.perms, "admin")) throw forbidden();
  const b = await body(req, z.object({ provider: z.enum(["stripe", "sslcommerz", "bkash"]).optional() }));
  const inv = await ctx.db.query.invoices.findFirst({ where: and(eq(schema.invoices.id, p.id!), eq(schema.invoices.workspaceId, ctx.workspace.id)) });
  if (!inv) throw notFound("Invoice");
  if (inv.status === "paid") throw new ApiError(409, "conflict", "Invoice already paid");
  const provider = b.provider ?? inv.provider;
  // platform billing account: the agency workspace (or this one) holds the payment integration
  const { findIntegration, pushVia } = await import("@/connectors");
  const agencyWs = ctx.workspace.agencyId ? (await ctx.db.select().from(schema.workspaces).where(eq(schema.workspaces.agencyId, ctx.workspace.agencyId)).orderBy(schema.workspaces.createdAt).limit(1))[0] : null;
  const billingCtx = agencyWs && agencyWs.id !== ctx.workspace.id ? { ...ctx, workspace: agencyWs } : ctx;
  const integ = await findIntegration(billingCtx, provider);
  if (!integ) throw new ApiError(409, "not_connected", `Connect ${provider} on the agency workspace to collect payments`);
  const r = await pushVia(billingCtx, integ, "checkout", { invoiceId: inv.id, amount: inv.amount, currency: inv.currency, description: `${ctx.workspace.name} · ${inv.period}`, successUrl: `${base()}/settings/billing?paid=${inv.id}`, cancelUrl: `${base()}/settings/billing`, ipnUrl: `${base()}/api/v1/hooks/${billingCtx.workspace.hookKey}/${provider}`, customerEmail: ctx.user?.email, customerName: ctx.workspace.name });
  return { data: r };
} });
route({ method: "POST", path: "/billing/invoices/:id/mark-paid", tag: "Billing", scope: "admin", internal: true, summary: "Mark paid (sandbox / offline payment)", handler: async (_r, ctx, p) => {
  needAgency(ctx);
  const { markInvoicePaid } = await import("@/lib/services/billing");
  await markInvoicePaid(ctx, p.id!, "manual");
} });

/* ---------------- agency & white-label (ADM-001/005) ---------------- */
route({ method: "GET", path: "/agency", tag: "Agency", scope: "admin", summary: "Agency branding and client sub-accounts with headline stats", handler: async (_r, ctx) => {
  needAgency(ctx);
  if (!ctx.workspace.agencyId) throw new ApiError(409, "no_agency", "This workspace has no agency");
  const agency = await ctx.db.query.agencies.findFirst({ where: eq(schema.agencies.id, ctx.workspace.agencyId) });
  const wss = await ctx.db.select().from(schema.workspaces).where(eq(schema.workspaces.agencyId, ctx.workspace.agencyId)).orderBy(schema.workspaces.name);
  const since = new Date(Date.now() - 30 * 86400000);
  const stats = await Promise.all(wss.map(async (w) => {
    const [c] = await ctx.db.select({ n: sql<number>`count(*)::int` }).from(schema.contacts).where(and(eq(schema.contacts.workspaceId, w.id), isNull(schema.contacts.deletedAt)));
    const [l] = await ctx.db.select({ n: sql<number>`count(DISTINCT contact_id)::int` }).from(schema.leadSources).where(and(eq(schema.leadSources.workspaceId, w.id), gte(schema.leadSources.capturedAt, since)));
    const [won] = await ctx.db.select({ n: sql<number>`count(*)::int`, v: sql<number>`COALESCE(sum(value),0)::bigint` }).from(schema.deals).where(and(eq(schema.deals.workspaceId, w.id), gte(schema.deals.wonAt, since)));
    const [sp] = await ctx.db.select({ s: sql<number>`COALESCE(sum(spend),0)::bigint` }).from(schema.adMetricsDaily).where(and(eq(schema.adMetricsDaily.workspaceId, w.id), gte(schema.adMetricsDaily.date, since.toISOString().slice(0, 10))));
    return { id: w.id, name: w.name, plan: w.plan, industry: w.settings?.industry ?? "general", currency: w.currency, timezone: w.timezone, contacts: c?.n ?? 0, leads30d: l?.n ?? 0, won30d: won?.n ?? 0, revenue30d: Number(won?.v ?? 0), spend30d: Number(sp?.s ?? 0) };
  }));
  return { data: { agency, workspaces: stats } };
} });
route({ method: "PATCH", path: "/agency", tag: "Agency", scope: "admin", summary: "Update white-label branding (logo, colour, product name, login domain)", body: z.object({ name: z.string().optional(), branding: z.object({ logoUrl: z.string().url().or(z.literal("")).optional(), primaryColor: z.string().regex(/^#[0-9a-fA-F]{6}$/).optional(), productName: z.string().max(40).optional(), loginDomain: z.string().optional(), hidePlatformBranding: z.boolean().optional() }) }), handler: async (req, ctx) => {
  needAgency(ctx);
  const b = await body(req, z.object({ name: z.string().optional(), branding: z.object({ logoUrl: z.string().url().or(z.literal("")).optional(), primaryColor: z.string().regex(/^#[0-9a-fA-F]{6}$/).optional(), productName: z.string().max(40).optional(), loginDomain: z.string().optional(), hidePlatformBranding: z.boolean().optional() }) }));
  const a = await ctx.db.query.agencies.findFirst({ where: eq(schema.agencies.id, ctx.workspace.agencyId ?? "") });
  if (!a) throw notFound("Agency");
  const [r] = await ctx.db.update(schema.agencies).set({ ...(b.name ? { name: b.name } : {}), branding: { ...a.branding, ...b.branding }, updatedAt: new Date() }).where(eq(schema.agencies.id, a.id)).returning();
  await audit(ctx, "update", "agency", a.id, a.branding, r!.branding);
  return { data: r };
} });
route({ method: "POST", path: "/agency/workspaces", tag: "Agency", scope: "admin", summary: "Create a client sub-account (workspace)", body: z.object({ name: z.string().min(2), timezone: z.string().default("Asia/Dhaka"), currency: z.enum(["BDT", "USD", "AUD"]).default("BDT"), locale: z.enum(["en", "bn"]).default("en"), industry: z.string().refine((v) => v in INDUSTRIES, "Unknown industry").default("general"), plan: z.enum(["starter", "growth", "agency"]).default("growth") }), handler: async (req, ctx) => {
  needAgency(ctx);
  const b = await body(req, z.object({ name: z.string().min(2), timezone: z.string().default("Asia/Dhaka"), currency: z.enum(["BDT", "USD", "AUD"]).default("BDT"), locale: z.enum(["en", "bn"]).default("en"), industry: z.string().refine((v) => v in INDUSTRIES, "Unknown industry").default("general"), plan: z.enum(["starter", "growth", "agency"]).default("growth") }));
  const ws = await createWorkspace(ctx.db, ctx.workspace.agencyId, b.name, b.timezone, b.currency, b.locale, b.industry);
  await ctx.db.update(schema.workspaces).set({ plan: b.plan }).where(eq(schema.workspaces.id, ws.id));
  if (ctx.user) await ctx.db.insert(schema.memberships).values({ workspaceId: ws.id, userId: ctx.user.id, roleId: (await systemRole(ctx.db, "workspace_admin")).id }).onConflictDoNothing();
  await audit(ctx, "create", "workspace", ws.id, undefined, { name: b.name });
  return { data: ws };
} });

export { readSecret };
