/** Account & workspace security API: two-factor methods, backup codes, trusted devices, sessions, admin recovery, security policy. */
import { z } from "zod";
import { and, desc, eq, gte, inArray, isNull, ne, 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 { verifyPassword, type Ctx } from "@/lib/auth";
import { normalizePhone } from "@/lib/util";
import { otpauthUrl } from "@/lib/crypto";
import {
  MFA_LABEL, MFA_TYPES, allowedTypes, backupCodesLeft, checkTotp, publicMethod, refreshMfaFlag, regenerateBackupCodes, rp, sendCode, startTotp,
  userMethods, verifyCode, webauthnRegister, webauthnRegistrationOptions, type MfaType,
} from "@/lib/security/mfa";
import { emailDeliveryConfigured, smsDeliveryConfigured } from "@/lib/security/deliver";
import { clientIp, ipAllowed, validIpEntry } from "@/lib/security/request";

const me = (ctx: Ctx) => { if (!ctx.user) throw forbidden("Sign in as a user to manage security"); return ctx.user; };
const loadUser = async (ctx: Ctx) => (await ctx.db.query.users.findFirst({ where: eq(schema.users.id, me(ctx).id) }))!;
const needAdmin = (ctx: Ctx) => { if (!can(ctx.perms, "admin", "edit")) throw forbidden("Admin access required"); };

function ensureAllowed(ctx: Ctx, type: MfaType) {
  if (!allowedTypes(ctx.workspace.settings?.security).includes(type)) throw new ApiError(403, "method_not_allowed", `${MFA_LABEL[type]} is not allowed in this workspace`);
}

/** Sensitive changes need the password again (or, for accounts without one, a session younger than 15 minutes). */
async function reauth(ctx: Ctx, password?: string) {
  const u = await loadUser(ctx);
  if (u.passwordHash) {
    if (!password || !(await verifyPassword(password, u.passwordHash))) throw new ApiError(401, "reauth_failed", "Enter your current password to confirm");
    return u;
  }
  const s = ctx.sessionId ? await ctx.db.query.sessions.findFirst({ where: eq(schema.sessions.id, ctx.sessionId) }) : null;
  if (!s || Date.now() - s.createdAt.getTime() > 15 * 60000) throw new ApiError(401, "reauth_required", "Sign in again to confirm this change");
  return u;
}

/** After the first verified method, issue backup codes once so users can't be locked out. */
async function onVerified(ctx: Ctx, type: string, methodId: string) {
  await refreshMfaFlag(ctx.db, me(ctx).id);
  if (ctx.sessionId) await ctx.db.update(schema.sessions).set({ mfaPassed: true }).where(eq(schema.sessions.id, ctx.sessionId));
  await audit(ctx, "mfa_method_added", "user", me(ctx).id, undefined, { type, methodId });
  const backupCodes = (await backupCodesLeft(ctx.db, me(ctx).id)) === 0 ? await regenerateBackupCodes(ctx.db, me(ctx).id) : null;
  return backupCodes;
}

route({ method: "GET", path: "/me/security", tag: "Security", internal: true, summary: "My two-factor methods, backup codes, trusted devices and sessions", handler: async (_r, ctx) => {
  const u = await loadUser(ctx);
  const methods = await userMethods(ctx.db, u);
  const devices = await ctx.db.select({ id: schema.trustedDevices.id, userAgent: schema.trustedDevices.userAgent, ip: schema.trustedDevices.ip, expiresAt: schema.trustedDevices.expiresAt, lastUsedAt: schema.trustedDevices.lastUsedAt, createdAt: schema.trustedDevices.createdAt }).from(schema.trustedDevices).where(and(eq(schema.trustedDevices.userId, u.id), gte(schema.trustedDevices.expiresAt, new Date()))).orderBy(desc(schema.trustedDevices.createdAt));
  const sessions = await ctx.db.select({ id: schema.sessions.id, userAgent: schema.sessions.userAgent, ip: schema.sessions.ip, createdAt: schema.sessions.createdAt, lastSeenAt: schema.sessions.lastSeenAt, mfaMethod: schema.sessions.mfaMethod, expiresAt: schema.sessions.expiresAt }).from(schema.sessions).where(and(eq(schema.sessions.userId, u.id), gte(schema.sessions.expiresAt, new Date()))).orderBy(desc(schema.sessions.createdAt)).limit(30);
  const sec = ctx.workspace.settings?.security ?? {};
  return { data: {
    email: u.email, phone: u.phone, hasPassword: !!u.passwordHash, mfaEnabled: methods.length > 0, mfaRequired: !!ctx.workspace.settings?.mfaRequired,
    methods: methods.map(publicMethod), backupCodesLeft: await backupCodesLeft(ctx.db, u.id),
    allowedMethods: allowedTypes(sec), delivery: { email: emailDeliveryConfigured() || process.env.NODE_ENV !== "production", sms: smsDeliveryConfigured() || process.env.NODE_ENV !== "production" },
    trustedDevices: devices, sessions: sessions.map((s) => ({ ...s, current: s.id === ctx.sessionId })), passwordChangedAt: u.passwordChangedAt,
  } };
} });

/* ---------------- authenticator app ---------------- */
route({ method: "POST", path: "/me/mfa/totp", tag: "Security", internal: true, summary: "Start authenticator-app enrolment (returns secret + otpauth URL)", handler: async (req, ctx) => {
  ensureAllowed(ctx, "totp");
  const b = (await req.json().catch(() => ({}))) as { label?: string };
  const u = me(ctx);
  const { method, secret } = await startTotp(ctx.db, u.id, typeof b.label === "string" ? b.label : undefined);
  return { data: { methodId: method.id, secret, otpauth: otpauthUrl(secret, u.email, process.env.NEXT_PUBLIC_PRODUCT_NAME ?? "Tempest Pulse") } };
} });
route({ method: "POST", path: "/me/mfa/totp/:id/verify", tag: "Security", internal: true, summary: "Confirm the authenticator app with a 6-digit code", body: z.object({ code: z.string().min(6).max(8) }), handler: async (req, ctx, p) => {
  const b = await body(req, z.object({ code: z.string().min(6).max(8) }));
  const m = await ctx.db.query.mfaMethods.findFirst({ where: and(eq(schema.mfaMethods.id, p.id!), eq(schema.mfaMethods.userId, me(ctx).id), eq(schema.mfaMethods.type, "totp")) });
  if (!m) throw notFound("Authenticator");
  if (!(await checkTotp(ctx.db, m, b.code))) throw new ApiError(400, "invalid_code", "That code is not valid — check the time on your phone is set automatically");
  await ctx.db.update(schema.mfaMethods).set({ verifiedAt: new Date() }).where(eq(schema.mfaMethods.id, m.id));
  return { data: { ok: true, backupCodes: await onVerified(ctx, "totp", m.id) } };
} });

/* ---------------- email & SMS ---------------- */
route({ method: "POST", path: "/me/mfa/email", tag: "Security", internal: true, summary: "Add an email address for sign-in codes (sends a code to confirm it)", body: z.object({ email: z.string().email().optional() }), handler: async (req, ctx) => {
  ensureAllowed(ctx, "email");
  const b = await body(req, z.object({ email: z.string().email().optional() }));
  const u = await loadUser(ctx);
  const target = (b.email ?? u.email).toLowerCase().trim();
  await ctx.db.delete(schema.mfaMethods).where(and(eq(schema.mfaMethods.userId, u.id), eq(schema.mfaMethods.type, "email"), isNull(schema.mfaMethods.verifiedAt)));
  const [m] = await ctx.db.insert(schema.mfaMethods).values({ userId: u.id, type: "email", label: "Email code", target }).returning();
  const r = await sendCode(ctx.db, u, m!, "enroll", ctx.sessionId);
  return { data: { methodId: m!.id, challengeId: r.challengeId, sentTo: target } };
} });
route({ method: "POST", path: "/me/mfa/sms", tag: "Security", internal: true, summary: "Add a mobile number for SMS codes (sends a code to confirm it)", body: z.object({ phone: z.string().min(6).max(20) }), handler: async (req, ctx) => {
  ensureAllowed(ctx, "sms");
  const b = await body(req, z.object({ phone: z.string().min(6).max(20) }));
  const phone = normalizePhone(b.phone, ctx.workspace.settings?.defaultCountryCode ?? "880");
  if (!phone) throw new ApiError(422, "invalid_phone", "Enter a valid mobile number");
  const u = await loadUser(ctx);
  await ctx.db.delete(schema.mfaMethods).where(and(eq(schema.mfaMethods.userId, u.id), eq(schema.mfaMethods.type, "sms"), isNull(schema.mfaMethods.verifiedAt)));
  const [m] = await ctx.db.insert(schema.mfaMethods).values({ userId: u.id, type: "sms", label: "SMS code", target: phone }).returning();
  const r = await sendCode(ctx.db, u, m!, "enroll", ctx.sessionId);
  return { data: { methodId: m!.id, challengeId: r.challengeId, sentTo: phone } };
} });
route({ method: "POST", path: "/me/mfa/:id/resend", tag: "Security", internal: true, summary: "Resend a confirmation code", handler: async (_r, ctx, p) => {
  const u = await loadUser(ctx);
  const m = await ctx.db.query.mfaMethods.findFirst({ where: and(eq(schema.mfaMethods.id, p.id!), eq(schema.mfaMethods.userId, u.id)) });
  if (!m) throw notFound("Method");
  const r = await sendCode(ctx.db, u, m, m.verifiedAt ? "step_up" : "enroll", ctx.sessionId);
  return { data: { challengeId: r.challengeId } };
} });
route({ method: "POST", path: "/me/mfa/:id/verify-code", tag: "Security", internal: true, summary: "Confirm an email or SMS method with the code sent to it", body: z.object({ challengeId: z.string().uuid(), code: z.string().min(6).max(8) }), handler: async (req, ctx, p) => {
  const b = await body(req, z.object({ challengeId: z.string().uuid(), code: z.string().min(6).max(8) }));
  const u = me(ctx);
  const m = await ctx.db.query.mfaMethods.findFirst({ where: and(eq(schema.mfaMethods.id, p.id!), eq(schema.mfaMethods.userId, u.id)) });
  if (!m) throw notFound("Method");
  await verifyCode(ctx.db, u.id, b.challengeId, b.code, m.id);
  await ctx.db.update(schema.mfaMethods).set({ verifiedAt: new Date() }).where(eq(schema.mfaMethods.id, m.id));
  if (m.type === "sms" && m.target) await ctx.db.update(schema.users).set({ phone: m.target }).where(eq(schema.users.id, u.id));
  return { data: { ok: true, backupCodes: await onVerified(ctx, m.type, m.id) } };
} });

/* ---------------- passkeys & security keys ---------------- */
route({ method: "POST", path: "/me/mfa/webauthn/options", tag: "Security", internal: true, summary: "Registration options for a passkey or security key", handler: async (req, ctx) => {
  ensureAllowed(ctx, "webauthn");
  return { data: await webauthnRegistrationOptions(ctx.db, await loadUser(ctx), rp(req)) };
} });
route({ method: "POST", path: "/me/mfa/webauthn/verify", tag: "Security", internal: true, summary: "Save a passkey or security key", body: z.object({ response: z.record(z.unknown()), label: z.string().max(60).optional() }), handler: async (req, ctx) => {
  ensureAllowed(ctx, "webauthn");
  const b = await body(req, z.object({ response: z.record(z.unknown()), label: z.string().max(60).optional() }));
  const m = await webauthnRegister(ctx.db, me(ctx).id, b.response, b.label, rp(req));
  return { data: { ok: true, method: publicMethod(m), backupCodes: await onVerified(ctx, "webauthn", m.id) } };
} });

/* ---------------- manage ---------------- */
route({ method: "PATCH", path: "/me/mfa/:id", tag: "Security", internal: true, summary: "Rename a method", body: z.object({ label: z.string().min(1).max(60) }), handler: async (req, ctx, p) => {
  const b = await body(req, z.object({ label: z.string().min(1).max(60) }));
  const [m] = await ctx.db.update(schema.mfaMethods).set({ label: b.label }).where(and(eq(schema.mfaMethods.id, p.id!), eq(schema.mfaMethods.userId, me(ctx).id))).returning();
  if (!m) throw notFound("Method");
  return { data: publicMethod(m) };
} });
route({ method: "POST", path: "/me/mfa/:id/remove", tag: "Security", internal: true, summary: "Remove a two-factor method (password required)", body: z.object({ password: z.string().optional() }), handler: async (req, ctx, p) => {
  const b = await body(req, z.object({ password: z.string().optional() }));
  const u = await reauth(ctx, b.password);
  const m = await ctx.db.query.mfaMethods.findFirst({ where: and(eq(schema.mfaMethods.id, p.id!), eq(schema.mfaMethods.userId, u.id)) });
  if (!m) throw notFound("Method");
  const remaining = (await userMethods(ctx.db, u)).filter((x) => x.id !== m.id);
  if (!remaining.length && ctx.workspace.settings?.mfaRequired) throw new ApiError(409, "mfa_required", "This workspace requires two-factor authentication — add another method before removing your last one");
  await ctx.db.delete(schema.mfaMethods).where(eq(schema.mfaMethods.id, m.id));
  if (!remaining.length) { await ctx.db.delete(schema.mfaBackupCodes).where(eq(schema.mfaBackupCodes.userId, u.id)); await ctx.db.delete(schema.trustedDevices).where(eq(schema.trustedDevices.userId, u.id)); }
  await refreshMfaFlag(ctx.db, u.id);
  await audit(ctx, "mfa_method_removed", "user", u.id, { type: m.type, methodId: m.id });
} });
route({ method: "POST", path: "/me/mfa/backup-codes", tag: "Security", internal: true, summary: "Generate 10 new backup codes (old ones stop working; password required)", body: z.object({ password: z.string().optional() }), handler: async (req, ctx) => {
  const b = await body(req, z.object({ password: z.string().optional() }));
  const u = await reauth(ctx, b.password);
  if (!(await userMethods(ctx.db, u)).length) throw new ApiError(409, "no_mfa", "Add a two-factor method first");
  const codes = await regenerateBackupCodes(ctx.db, u.id);
  await audit(ctx, "mfa_backup_codes_regenerated", "user", u.id);
  return { data: { codes } };
} });

/* ---------------- devices & sessions ---------------- */
route({ method: "DELETE", path: "/me/trusted-devices/:id", tag: "Security", internal: true, summary: "Forget a remembered device", handler: async (_r, ctx, p) => {
  await ctx.db.delete(schema.trustedDevices).where(and(eq(schema.trustedDevices.id, p.id!), eq(schema.trustedDevices.userId, me(ctx).id)));
} });
route({ method: "POST", path: "/me/trusted-devices/revoke-all", tag: "Security", internal: true, summary: "Forget all remembered devices", handler: async (_r, ctx) => {
  await ctx.db.delete(schema.trustedDevices).where(eq(schema.trustedDevices.userId, me(ctx).id));
  await audit(ctx, "trusted_devices_revoked", "user", me(ctx).id);
} });
route({ method: "POST", path: "/me/sessions/:id/revoke", tag: "Security", internal: true, summary: "Sign out one session", handler: async (_r, ctx, p) => {
  if (p.id === ctx.sessionId) throw new ApiError(409, "conflict", "Use Sign out to end your current session");
  await ctx.db.delete(schema.sessions).where(and(eq(schema.sessions.id, p.id!), eq(schema.sessions.userId, me(ctx).id)));
  await audit(ctx, "session_revoked", "user", me(ctx).id, undefined, { sessionId: p.id });
} });
route({ method: "POST", path: "/me/sessions/revoke-others", tag: "Security", internal: true, summary: "Sign out everywhere else", handler: async (_r, ctx) => {
  const r = await ctx.db.delete(schema.sessions).where(and(eq(schema.sessions.userId, me(ctx).id), ne(schema.sessions.id, ctx.sessionId ?? "00000000-0000-0000-0000-000000000000"))).returning({ id: schema.sessions.id });
  await audit(ctx, "sessions_revoked", "user", me(ctx).id, undefined, { count: r.length });
  return { data: { revoked: r.length } };
} });

/* ---------------- admin recovery ---------------- */
async function memberOf(ctx: Ctx, userId: string) {
  const m = await ctx.db.query.memberships.findFirst({ where: and(eq(schema.memberships.workspaceId, ctx.workspace.id), eq(schema.memberships.userId, userId)) });
  if (!m) throw notFound("Member");
  const u = await ctx.db.query.users.findFirst({ where: eq(schema.users.id, userId) });
  if (u?.isAgencyAdmin && !ctx.user?.isAgencyAdmin) throw forbidden("Only agency admins can change an agency admin's security");
  return u!;
}
route({ method: "POST", path: "/users/:id/mfa/reset", tag: "Security", scope: "admin", summary: "Admin: reset a member's two-factor (lost phone) — signs them out everywhere", handler: async (_r, ctx, p) => {
  needAdmin(ctx);
  if (p.id === ctx.user?.id) throw new ApiError(409, "conflict", "Use your own security settings");
  const u = await memberOf(ctx, p.id!);
  await ctx.db.delete(schema.mfaMethods).where(eq(schema.mfaMethods.userId, u.id));
  await ctx.db.delete(schema.mfaBackupCodes).where(eq(schema.mfaBackupCodes.userId, u.id));
  await ctx.db.delete(schema.trustedDevices).where(eq(schema.trustedDevices.userId, u.id));
  await ctx.db.delete(schema.sessions).where(eq(schema.sessions.userId, u.id));
  await ctx.db.update(schema.users).set({ mfaEnabled: false, mfaSecret: null }).where(eq(schema.users.id, u.id));
  await audit(ctx, "mfa_reset_by_admin", "user", u.id);
} });
route({ method: "POST", path: "/users/:id/unlock", tag: "Security", scope: "admin", summary: "Admin: unlock an account locked after failed sign-ins", handler: async (_r, ctx, p) => {
  needAdmin(ctx);
  const u = await memberOf(ctx, p.id!);
  await ctx.db.update(schema.users).set({ lockedUntil: null, failedLogins: 0 }).where(eq(schema.users.id, u.id));
  await audit(ctx, "account_unlocked", "user", u.id);
} });
route({ method: "POST", path: "/users/:id/sessions/revoke", tag: "Security", scope: "admin", summary: "Admin: sign a member out of every session", handler: async (_r, ctx, p) => {
  needAdmin(ctx);
  const u = await memberOf(ctx, p.id!);
  await ctx.db.delete(schema.sessions).where(eq(schema.sessions.userId, u.id));
  await audit(ctx, "sessions_revoked_by_admin", "user", u.id);
} });

/* ---------------- workspace security policy ---------------- */
const policyIn = z.object({
  mfaRequired: z.boolean().optional(),
  allowedMfaMethods: z.array(z.enum(["totp", "email", "sms", "webauthn"])).min(1).optional(),
  ipAllowlist: z.array(z.string().max(64)).max(100).optional(),
  passwordMinLength: z.number().int().min(10).max(64).optional(),
  loginAlerts: z.boolean().optional(),
  trustedDeviceDays: z.number().int().min(0).max(90).optional(),
  sessionTimeoutMinutes: z.number().int().min(15).max(60 * 24 * 30).optional(),
  confirmIpLockout: z.boolean().optional(),
});
route({ method: "GET", path: "/security/overview", tag: "Security", scope: "admin", summary: "Workspace security posture: 2FA coverage, locked accounts, recent sign-in events", handler: async (_r, ctx) => {
  needAdmin(ctx);
  const members = await ctx.db.select({ id: schema.users.id, name: schema.users.name, email: schema.users.email, mfaEnabled: schema.users.mfaEnabled, lockedUntil: schema.users.lockedUntil, lastLoginAt: schema.users.lastLoginAt, status: schema.users.status })
    .from(schema.memberships).innerJoin(schema.users, eq(schema.users.id, schema.memberships.userId)).where(and(eq(schema.memberships.workspaceId, ctx.workspace.id), eq(schema.memberships.active, true)));
  const ids = members.map((m) => m.id);
  const methods = ids.length ? await ctx.db.select({ u: schema.mfaMethods.userId, t: schema.mfaMethods.type }).from(schema.mfaMethods).where(and(inArray(schema.mfaMethods.userId, ids), sql`${schema.mfaMethods.verifiedAt} IS NOT NULL`)) : [];
  const events = await ctx.db.select().from(schema.auditLogs).where(and(eq(schema.auditLogs.workspaceId, ctx.workspace.id), inArray(schema.auditLogs.action, ["login", "login_failed", "account_locked", "login_blocked_locked", "mfa_passed", "mfa_failed", "mfa_method_added", "mfa_method_removed", "mfa_reset_by_admin", "password_change", "sessions_revoked", "account_unlocked", "security_policy_updated"]))).orderBy(desc(schema.auditLogs.at)).limit(100);
  const sec = ctx.workspace.settings?.security ?? {};
  return { data: {
    policy: { mfaRequired: !!ctx.workspace.settings?.mfaRequired, allowedMfaMethods: allowedTypes(sec), ipAllowlist: sec.ipAllowlist ?? [], passwordMinLength: sec.passwordMinLength ?? 10, loginAlerts: sec.loginAlerts !== false, trustedDeviceDays: sec.trustedDeviceDays ?? 30, sessionTimeoutMinutes: ctx.workspace.settings?.sessionTimeoutMinutes ?? 60 * 24 * 7 },
    members: members.map((m) => ({ ...m, methods: [...new Set(methods.filter((x) => x.u === m.id).map((x) => x.t))], locked: !!m.lockedUntil && m.lockedUntil > new Date() })),
    coverage: members.length ? Math.round((members.filter((m) => m.mfaEnabled).length / members.length) * 100) : 0,
    events, yourIp: ctx.ip ?? null, delivery: { email: emailDeliveryConfigured(), sms: smsDeliveryConfigured() }, availableMethods: MFA_TYPES,
  } };
} });
route({ method: "PATCH", path: "/security/policy", tag: "Security", scope: "admin", summary: "Update workspace security policy (2FA requirement and allowed methods, IP allowlist, password length, login alerts, trusted devices, session timeout)", body: policyIn, handler: async (req, ctx) => {
  needAdmin(ctx);
  const b = await body(req, policyIn);
  if (b.ipAllowlist) {
    const bad = b.ipAllowlist.filter((x) => x.trim() && !validIpEntry(x));
    if (bad.length) throw new ApiError(422, "validation_failed", `Not a valid IP or IPv4 range: ${bad.join(", ")}`);
    const ip = ctx.ip ?? clientIp(req.headers);
    if (!ipAllowed(ip, b.ipAllowlist) && !b.confirmIpLockout) throw new ApiError(409, "would_lock_out", `Your current IP (${ip ?? "unknown"}) is not on this list — you would lock yourself out. Add it, or confirm.`);
  }
  if (b.mfaRequired && !ctx.user?.mfaEnabled) throw new ApiError(409, "enable_mfa_first", "Turn on two-factor for your own account before requiring it for everyone");
  const prev = ctx.workspace.settings ?? {};
  const security = { ...(prev.security ?? {}), ...(b.allowedMfaMethods ? { allowedMfaMethods: b.allowedMfaMethods } : {}), ...(b.ipAllowlist ? { ipAllowlist: b.ipAllowlist.map((x) => x.trim()).filter(Boolean) } : {}), ...(b.passwordMinLength ? { passwordMinLength: b.passwordMinLength } : {}), ...(b.loginAlerts !== undefined ? { loginAlerts: b.loginAlerts } : {}), ...(b.trustedDeviceDays !== undefined ? { trustedDeviceDays: b.trustedDeviceDays } : {}) };
  const settings = { ...prev, security, ...(b.mfaRequired !== undefined ? { mfaRequired: b.mfaRequired } : {}), ...(b.sessionTimeoutMinutes ? { sessionTimeoutMinutes: b.sessionTimeoutMinutes } : {}) };
  const [w] = await ctx.db.update(schema.workspaces).set({ settings, updatedAt: new Date() }).where(eq(schema.workspaces.id, ctx.workspace.id)).returning();
  await audit(ctx, "security_policy_updated", "workspace", ctx.workspace.id, prev, settings);
  return { data: w!.settings };
} });

/* ---------------- personal dashboard layout ---------------- */
route({ method: "PUT", path: "/me/dashboard", tag: "Security", internal: true, summary: "Save my dashboard layout (order + hidden widgets) for this workspace, or reset to the industry default", body: z.object({ order: z.array(z.string().max(40)).max(40).optional(), hidden: z.array(z.string().max(40)).max(40).optional(), reset: z.boolean().optional() }), handler: async (req, ctx) => {
  const b = await body(req, z.object({ order: z.array(z.string().max(40)).max(40).optional(), hidden: z.array(z.string().max(40)).max(40).optional(), reset: z.boolean().optional() }));
  const { WIDGETS } = await import("@/lib/dashboard");
  const clean = (xs?: string[]) => [...new Set((xs ?? []).filter((x) => x in WIDGETS))];
  const layout = b.reset ? null : { order: clean(b.order), hidden: clean(b.hidden) };
  await ctx.db.update(schema.memberships).set({ dashboardLayout: layout }).where(and(eq(schema.memberships.workspaceId, ctx.workspace.id), eq(schema.memberships.userId, me(ctx).id)));
  return { data: layout };
} });
