/**
 * Invoices module gate. Port-scoped on/off switch for the standalone
 * `/invoices` flow.
 *
 * Audit conclusion (2026-05-27, launch-readiness Initiative 1c): the
 * `invoices` schema is rich (invoices + invoice_line_items +
 * invoice_expenses + send + payment + PDF) but the dev DB has zero rows
 * and no rep ever clicks through. The canonical "money received" path
 * is the per-interest Payments tab (records into `payments` and auto-
 * advances pipeline). The standalone /invoices flow is parallel
 * infrastructure for employee expense reports + the rare case where a
 * port operator wants to invoice a client directly from the CRM.
 *
 * Defaults to DISABLED so new ports launch with a clean surface; admins
 * can opt in from Admin → Operations. Existing ports keep the legacy
 * surface visible until explicitly turned off.
 *
 * Behaviour when disabled:
 *  - the (already-removed) sidebar entry stays hidden
 *  - the /invoices and /invoices/new and /invoices/[id] routes render a
 *    "Module disabled" page instead of the full form
 *  - the API endpoints (`/api/v1/invoices/*`) still respond so any
 *    historical PDF links / webhook callbacks keep resolving
 *  - existing invoice rows are preserved
 */

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

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

export async function isInvoicesModuleEnabled(portId: string): Promise<boolean> {
  const settingRow = await db
    .select({ value: systemSettings.value })
    .from(systemSettings)
    .where(
      and(
        eq(systemSettings.key, 'invoices_module_enabled'),
        or(eq(systemSettings.portId, portId), isNull(systemSettings.portId)),
      ),
    )
    .limit(1);
  // Stored JSONB shape is the raw boolean. The registry default is `false`,
  // so a missing row → disabled. Anything other than an explicit `true`
  // keeps the module hidden.
  return settingRow[0]?.value === true;
}
