/**
 * auditor-search-idor smoke — guards the 2026-06-01 IDOR fix on
 * /api/search.
 *
 * Auditor finding: the search route's monitor + incident queries had
 * NO scoping for non-ADMIN roles. A VIEWER/EDITOR could surface names,
 * URLs, hostnames of monitors owned by other users plus titles of
 * incidents in regions they don't manage.
 *
 * Fix: route.ts now adds `userId` to the monitor query and an
 * incident-region filter (matching the incidents GET pattern) for
 * non-ADMIN roles. This smoke walks the source and asserts both
 * branches stay in place so a future refactor can't silently regress.
 */
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/search/route.ts');

    assert('search route: isAdmin gate is computed',
        /const isAdmin\s*=\s*session\.user\.role\s*===\s*"ADMIN"/.test(route),
        'search/route.ts no longer computes isAdmin from session.user.role.');

    assert('search route: monitor query is owner-scoped for non-ADMIN',
        /isAdmin\s*\?\s*\{\}\s*:\s*\{\s*userId\s*\}/.test(route),
        'search/route.ts no longer adds { userId } to monitor.findMany when non-ADMIN — IDOR may have regressed.');

    assert('search route: incident query is region-scoped for non-ADMIN',
        /incidentRegionFilter/.test(route) && /countries:\s*\{\s*some:/.test(route),
        'search/route.ts no longer adds an incidentRegionFilter via countries.some — IDOR may have regressed.');

    assert('search route: Global fallback when user has no countries',
        /some:\s*\{\s*name:\s*"Global"\s*\}/.test(route),
        'search/route.ts no longer falls back to Global incidents when user has no countries.');

    // Unit-test coverage exists and asserts the right thing.
    const test = read('src/app/api/search/__tests__/route.test.ts');
    assert('search route: unit test exists',
        /auditor 2026-06-01 IDOR fix/.test(test),
        'src/app/api/search/__tests__/route.test.ts is missing or no longer references the audit.');
    assert('search route: unit test asserts VIEWER monitors scoped to userId',
        /monitorCall\.where\.userId/.test(test),
        'search route unit test no longer asserts the userId scope on monitors.');

    ok('auditor-search-idor', '/api/search scopes monitors + incidents for non-ADMIN');
}

main();
