/**
 * server-passenger-env-loading smoke — guards the fix for the
 * 2026-05-31 prod incident where 2FA enforcement was silently
 * disabled because Passenger boots `server.js` directly (not
 * `next start`), so Next.js's usual auto-loading of .env never
 * fires. AUTH_2FA_ENFORCED lived only in .env on the prod host,
 * cPanel Application Manager didn't have it, and the resulting
 * runtime process.env saw the var as undefined — login bypassed
 * the 2FA challenge and the enrollment redirect never fired.
 *
 * Fix: server.js now calls @next/env's loadEnvConfig BEFORE any
 * other code reads process.env. This smoke is structural — it
 * walks server.js and asserts the call is present and positioned
 * before any other env-sensitive code.
 */
import './_lib';
import { ok, fail } from './_lib';
import { readFileSync } from 'fs';
import path from 'path';

const ROOT = path.resolve(__dirname, '../..');
const read = (rel: string): string => readFileSync(path.join(ROOT, rel), 'utf8');

function assert(label: string, cond: boolean, detail: string): void {
    if (!cond) fail(label, detail);
    ok(label);
}

function main(): void {
    const server = read('server.js');

    assert('server.js imports loadEnvConfig from @next/env',
        /require\(['"]@next\/env['"]\)/.test(server) && /loadEnvConfig/.test(server),
        'server.js no longer imports loadEnvConfig from @next/env — env vars in .env will not reach Passenger runtime.');

    assert('server.js calls loadEnvConfig(process.cwd())',
        /loadEnvConfig\(\s*process\.cwd\(\)\s*\)/.test(server),
        'server.js no longer calls loadEnvConfig(process.cwd()) — the bare import is dead code.');

    // Position check: loadEnvConfig must run before `next` is required
    // (else next reads stale process.env when it lazy-loads modules
    // that touch env.ts at boot). Verify by index of first occurrence.
    const loadIdx = server.indexOf('loadEnvConfig(');
    const nextIdx = server.indexOf("require('next')");
    assert('loadEnvConfig runs before next is required',
        loadIdx > 0 && nextIdx > 0 && loadIdx < nextIdx,
        `loadEnvConfig must appear before require('next') in server.js (loadIdx=${loadIdx}, nextIdx=${nextIdx}).`);

    ok('server-passenger-env-loading', '.env reaches Passenger runtime via @next/env');
}

main();
