/**
 * P0-11 smoke test — security response headers.
 *
 * Two modes:
 *  - Default: statically reads next.config.ts and asserts each required
 *    header key is declared in the headers() block. Offline-safe.
 *  - With SMOKE_LIVE=1: also hits the running dev server at $SMOKE_BASE_URL
 *    and asserts the headers are actually returned.
 */
import './_lib';
import { ok, fail, BASE_URL } from './_lib';
import { readFileSync } from 'fs';
import path from 'path';

const REQUIRED = [
    'strict-transport-security',
    'x-content-type-options',
    'x-frame-options',
    'referrer-policy',
    'permissions-policy',
    'content-security-policy',
];

function staticCheck(): void {
    const cfgPath = path.resolve(__dirname, '../../next.config.ts');
    const src = readFileSync(cfgPath, 'utf8');
    for (const key of REQUIRED) {
        const re = new RegExp(key, 'i');
        if (!re.test(src)) fail(`static: declares ${key}`, `not present in next.config.ts`);
        ok(`Declares ${key}`);
    }
}

async function liveCheck(): Promise<void> {
    const res = await fetch(BASE_URL);
    for (const key of REQUIRED) {
        const value = res.headers.get(key);
        if (!value) fail(`live: ${key}`, `not present in response from ${BASE_URL}`);
        ok(`Live ${key}`, value!);
    }
}

async function main(): Promise<void> {
    staticCheck();
    if (process.env.SMOKE_LIVE === '1') {
        await liveCheck();
    } else {
        ok('Live check skipped', 'set SMOKE_LIVE=1 with dev server running to enable');
    }
    ok('P0-11 headers', 'all required security headers declared');
}

main().catch((err) => fail('P0-11 headers', String(err)));
