/**
 * exec-report-cache smoke — /api/reports/executive must serve a shared,
 * short-TTL cached payload with single-flight de-duplication.
 *
 * Run: npx tsx scripts/smoke/exec-report-cache.ts
 *
 * Why (2026-05-30): the executive report aggregates the heartbeat history and
 * is polled every 30s by every open Executive tab AND the Wall. On the live
 * box this pegged the Node process at ~5 cores / 4.7 GB (load avg 7) because
 * each client triggered the full heavy build independently. A module-level
 * cache (EXEC_CACHE_TTL_MS) + in-flight promise collapses all of them into at
 * most one heavy build per TTL. This smoke guards that wiring so a future
 * refactor can't silently drop it and reinstate the stampede.
 */
import './_lib';
import { ok, fail } from './_lib';
import { readFileSync } from 'fs';
import path from 'path';

const ROUTE = path.resolve(__dirname, '../../src/app/api/reports/executive/route.ts');

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

function main(): void {
    const src = readFileSync(ROUTE, 'utf8');

    assert('cache TTL constant present', /EXEC_CACHE_TTL_MS\s*=\s*\d/.test(src),
        'EXEC_CACHE_TTL_MS not found — the shared cache TTL was removed.');
    assert('module-level cache slot', /_execCache\b/.test(src),
        '_execCache not found — the cached payload slot was removed.');
    assert('single-flight in-flight promise', /_execInflight\b/.test(src),
        '_execInflight not found — concurrent cache-misses would stampede the DB.');
    assert('fresh-cache short-circuit', /_execCache\s*&&\s*Date\.now\(\)\s*-\s*_execCache\.at\s*<\s*EXEC_CACHE_TTL_MS/.test(src),
        'fresh-cache check not found — every request would recompute.');
    assert('heavy build extracted to buildExecutiveMetrics', /async function buildExecutiveMetrics\s*\(/.test(src),
        'buildExecutiveMetrics() not found — the cache wraps nothing.');
    // The auth gate must still run BEFORE any cache hit (no leaking metrics to
    // unauthorized callers).
    assert('auth precedes cache short-circuit', src.indexOf('if (!authorized)') < src.indexOf('Date.now() - _execCache.at'),
        'the cache short-circuit must come AFTER the auth gate so metrics never reach unauthorized callers.');

    ok('exec-report-cache', 'executive report is cached (TTL + single-flight) behind the auth gate');
}

main();
