/**
 * T6 (2026-06-02): boot-time schema-drift guard.
 *
 * deploy.sh runs `prisma migrate deploy` before restart (and a smoke enforces
 * that). But the cPanel/Passenger host boots server.js directly, so a bare
 * `git pull` + restart that BYPASSES deploy.sh serves new code against an old
 * schema — the silent failure behind the 2026-05-31 login outage. This logs
 * loudly when on-disk migrations have not been applied. It never blocks boot
 * (mirrors audit-chain-boot-verify): the operator's logs/alerts decide.
 */
import { getPendingMigrations } from '@/lib/db/migration-drift';
import { log } from '@/lib/observability/logger';

export async function checkSchemaDriftAtBoot(): Promise<void> {
    try {
        const pending = await getPendingMigrations();
        if (pending.length > 0) {
            const msg =
                `SCHEMA DRIFT: ${pending.length} unapplied migration(s) ` +
                `[${pending.join(', ')}] — the app is serving against an OUTDATED ` +
                `schema. Run \`npx prisma migrate deploy\` (or ./deploy.sh). This is ` +
                `the failure mode behind the 2026-05-31 login outage.`;
            log.error({ pending }, msg);
            // Raw console.error too, so it surfaces in the Passenger app log
            // even if structured log output is level-filtered.
            console.error('[schema-drift] ' + msg);
        } else {
            log.info({}, '[schema-drift] schema up to date — no pending migrations');
        }
    } catch (err) {
        // Best-effort. A legacy DB whose _prisma_migrations table was never
        // baselined lands here; that is a separate runbook, not a boot blocker.
        log.warn(
            { err: (err as Error).message },
            '[schema-drift] boot check skipped (could not read migration state)',
        );
    }
}
