/**
 * Email notification preferences
 * ──────────────────────────────
 * Per-user opt-in/out toggles for outbound email channels. Lives at
 * User.emailPrefs (Json column) — see prisma/schema.prisma. This file
 * is the single source of truth for the shape, defaults, and the
 * merge helper that turns a partial / legacy stored value into a
 * fully populated EmailPrefs object.
 *
 * Pulled out of the API route file because Next.js route files can
 * only export HTTP method handlers + route config; non-handler
 * exports (interfaces, helpers) trigger a build error.
 */

export interface EmailPrefs {
  signalAlerts: boolean;
  weeklyDigest: boolean;
  auditCompletion: boolean;
  reportReady: boolean;
  teamActivity: boolean;
}

/** Default preferences — only applied when a user has never touched
 *  the toggles. Missing keys default to true for the three core
 *  channels (signal / audit / report) so a new user doesn't go dark
 *  on important events; team activity defaults false because most
 *  agencies don't want an email every seat tweak. */
export const DEFAULT_EMAIL_PREFS: EmailPrefs = {
  signalAlerts: true,
  weeklyDigest: true,
  auditCompletion: true,
  reportReady: true,
  teamActivity: false,
};

/** Merge a stored (possibly partial / legacy) value into a fully
 *  populated EmailPrefs. Read by the alert sender + report
 *  generator before dispatching so partial PATCHes never reset the
 *  unspecified channels back to defaults. */
export function mergePrefs(stored: unknown): EmailPrefs {
  if (!stored || typeof stored !== "object") return { ...DEFAULT_EMAIL_PREFS };
  const s = stored as Partial<EmailPrefs>;
  return {
    signalAlerts:    typeof s.signalAlerts === "boolean"    ? s.signalAlerts    : DEFAULT_EMAIL_PREFS.signalAlerts,
    weeklyDigest:    typeof s.weeklyDigest === "boolean"    ? s.weeklyDigest    : DEFAULT_EMAIL_PREFS.weeklyDigest,
    auditCompletion: typeof s.auditCompletion === "boolean" ? s.auditCompletion : DEFAULT_EMAIL_PREFS.auditCompletion,
    reportReady:     typeof s.reportReady === "boolean"     ? s.reportReady     : DEFAULT_EMAIL_PREFS.reportReady,
    teamActivity:    typeof s.teamActivity === "boolean"    ? s.teamActivity    : DEFAULT_EMAIL_PREFS.teamActivity,
  };
}
