/**
 * Expenses module gate. Port-scoped on/off switch for the entire expense
 * + receipt-upload surface (sidebar entries, /expenses routes, mobile
 * scanner, receipt-upload explainer).
 *
 * Defaults to ENABLED so existing ports keep the feature on deploy.
 * When an admin turns it off:
 *  - the sidebar entries (Expenses + How to upload receipts) disappear
 *    via the port-resolved expensesModuleByPort prop on the layout
 *  - the expenses routes render a "Module disabled" page instead of
 *    the real content, so bookmarks land somewhere meaningful and the
 *    operator can re-enable from one click
 *  - previously-recorded expense rows are preserved (no destructive
 *    cleanup) so re-enabling restores everything
 */

import { and, eq, isNull, or } from 'drizzle-orm';

import { db } from '@/lib/db';
import { systemSettings } from '@/lib/db/schema/system';

/**
 * Resolve whether the Expenses module is currently active for the given
 * port. Reads from `system_settings.expenses_module_enabled` (port-
 * scoped row first, then global row, then registry default = true).
 *
 * Defaulting to enabled mirrors how the feature behaved before the
 * toggle existed: deploying this change to a port that has never
 * configured the setting leaves the feature visible.
 */
export async function isExpensesModuleEnabled(portId: string): Promise<boolean> {
  const settingRow = await db
    .select({ value: systemSettings.value })
    .from(systemSettings)
    .where(
      and(
        eq(systemSettings.key, 'expenses_module_enabled'),
        or(eq(systemSettings.portId, portId), isNull(systemSettings.portId)),
      ),
    )
    .limit(1);
  // Stored JSONB shape is the raw boolean (`true` / `false`); no
  // unwrapping needed because the admin-settings PUT handler writes the
  // primitive directly.
  if (settingRow[0]?.value === false) return false;
  // Any value other than an explicit `false` (incl. missing row, true,
  // unrecognized shape) means enabled - matches the registry default.
  return true;
}
