/**
 * auditor-p1b smoke — guards two fixes from the external review's P1 batch:
 *
 *  1. Incident WRITES enforce region-ownership (object-level authz). The GET
 *     path scoped non-ADMINs to their countries, but POST/PUT gated on role
 *     only, so an EDITOR could create/re-target an incident to regions they
 *     don't manage (latent IDOR). Both write paths must call the guard.
 *  2. The jest run is memory-bounded (ts-jest isolatedModules + a worker memory
 *     cap) so the full ~145-suite suite stops OOMing and is a real gate again.
 */
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 route = read('src/app/api/incidents/route.ts');
    // The guard must be invoked on BOTH write paths (≥2 call sites).
    const calls = (route.match(/assertIncidentRegionAccess\(/g) ?? []).length;
    assert('incident writes call the region-access guard (POST + PUT)', calls >= 2,
        `incidents/route.ts has ${calls} assertIncidentRegionAccess call(s); expected ≥2 (POST create + PUT update).`);

    const helper = read('src/lib/authorization/incident-region-access.ts');
    assert('region-access guard returns 403 on out-of-scope regions', /403/.test(helper) && /regionIdsWithinAllowed/.test(helper),
        'incident-region-access.ts no longer rejects out-of-scope regions with 403.');

    const jest = read('jest.config.js');
    assert('jest uses ts-jest isolatedModules (OOM guard)', /isolatedModules:\s*true/.test(jest),
        'jest.config.js no longer sets ts-jest isolatedModules — the full suite will OOM again.');
    assert('jest caps worker memory', /workerIdleMemoryLimit/.test(jest),
        'jest.config.js no longer sets workerIdleMemoryLimit.');

    ok('auditor-p1b-incident-authz', 'incident writes region-gated; jest memory-bounded');
}

main();
