/**
 * Maintenance module gate. Port-scoped on/off switch for the per-berth
 * maintenance surface (the berth "Maintenance" tab, its log API, and the
 * maintenance-reminder notification preference).
 *
 * Defaults to ENABLED so existing ports keep the feature on deploy.
 * When an admin turns it off:
 *  - the Maintenance tab disappears from the berth detail page (gated via
 *    the port-resolved maintenanceModuleByPort prop on the layout →
 *    port-provider → `useMaintenanceModuleEnabled()`)
 *  - the maintenance log routes reject reads/writes at the boundary
 *    (`assertMaintenanceModuleEnabled` → 404)
 *  - previously-recorded maintenance logs 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';
import { NotFoundError } from '@/lib/errors';

/**
 * Resolve whether the Maintenance module is currently active for the given
 * port. Reads from `system_settings.maintenance_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 isMaintenanceModuleEnabled(portId: string): Promise<boolean> {
  const settingRow = await db
    .select({ value: systemSettings.value })
    .from(systemSettings)
    .where(
      and(
        eq(systemSettings.key, 'maintenance_module_enabled'),
        or(eq(systemSettings.portId, portId), isNull(systemSettings.portId)),
      ),
    )
    .limit(1);
  // Stored JSONB shape is the raw boolean; only an explicit `false` turns
  // the module off — missing row / true / unrecognized shape => enabled.
  if (settingRow[0]?.value === false) return false;
  return true;
}

/**
 * Throw `NotFoundError` (→ 404) when the Maintenance module is disabled.
 * Defense-in-depth for the maintenance log routes; the UI independently
 * hides the tab so a rep never sees a link that would 404.
 */
export async function assertMaintenanceModuleEnabled(portId: string): Promise<void> {
  const enabled = await isMaintenanceModuleEnabled(portId);
  if (!enabled) {
    throw new NotFoundError('Maintenance module is not enabled for this port.');
  }
}
