/**
 * audit3-followup (2026-05-30): the Executive dashboard is login-less via the
 * executive_display token system (admin-minted, device-locked) — replacing the
 * old executive_session JWT handoff, which minted a token for ANY authenticated
 * user with no role claim (privilege escalation — punch-list #1).
 *
 * Structural assertions:
 *   1. The legacy auth files are GONE (handoff, session, executive-auth.ts).
 *   2. proxy.ts no longer references executive_session / handleExecutiveAuth,
 *      and the matcher excludes the executive paths.
 *   3. Token generation is ADMIN-only; exchange is device-locked.
 *   4. /api/reports/executive authorizes via getExecutiveDisplaySession.
 *   5. The /executive layout is gated by ExecutiveAuthWrapper.
 */
import './_lib';
import { ok, fail } from './_lib';
import { existsSync, readFileSync } from 'fs';
import path from 'path';

const ROOT = path.resolve(__dirname, '../..');
const read = (rel: string) => readFileSync(path.join(ROOT, rel), 'utf8');
const has = (rel: string) => existsSync(path.join(ROOT, rel));
function assert(label: string, cond: boolean, detail = '') {
    if (!cond) fail(label, detail || 'assertion failed');
    ok(label);
}

function main(): void {
    // 1. Legacy JWT handoff removed.
    assert('exec-tokens: legacy executive-handoff route removed', !has('src/app/api/auth/executive-handoff/route.ts'));
    assert('exec-tokens: legacy executive-session route removed', !has('src/app/api/auth/executive-session/route.ts'));
    assert('exec-tokens: legacy executive-auth.ts removed', !has('src/lib/executive-auth.ts'));

    // 2. proxy.ts cleaned. The login-less EXECUTIVE API paths stay
    //    matcher-excluded (self-authorizing JSON; withAuth must not run on
    //    them). The /executive PAGE routes are NOT matcher-excluded — they
    //    run the auth-bypassed public-page branch so they receive the CSP
    //    nonce (wall-blank fix 2026-05-30); without it 'strict-dynamic'
    //    blocks their nonce-less <script> tags → blank dark screen.
    const proxy = read('src/proxy.ts');
    assert('exec-tokens: proxy has no executive_session cookie read', !/cookies\.get\(["']executive_session/.test(proxy));
    assert('exec-tokens: handleExecutiveAuth function removed', !/function\s+handleExecutiveAuth/.test(proxy));
    assert('exec-tokens: proxy matcher excludes /api/executive', /api\/executive/.test(proxy));
    assert('exec-tokens: proxy matcher excludes /api/reports/executive', /api\/reports\/executive/.test(proxy));
    // /executive pages auth-bypassed (public-page branch), NOT matcher-excluded.
    assert('exec-tokens: /executive pages auth-bypassed for CSP nonce', /isExecutivePage/.test(proxy) && /startsWith\(['"]\/executive\/['"]\)/.test(proxy));
    // Guard the regression: the standalone `|executive|` page exclusion must NOT
    // come back (it would strip the nonce again). api/executive| is allowed.
    assert('exec-tokens: standalone /executive page exclusion not present in matcher', !/\|executive\|_next/.test(proxy));

    // 3. Helper + routes.
    const helper = read('src/lib/executive-display-auth.ts');
    assert('exec-tokens: helper exports getExecutiveDisplaySession', /export\s+async\s+function\s+getExecutiveDisplaySession/.test(helper));
    assert('exec-tokens: scope is executive_display', /executive_display/.test(helper));
    assert('exec-tokens: helper enforces device lock', /lockedDeviceId\s*!==\s*currentDeviceId/.test(helper));

    const authRoute = read('src/app/api/executive/auth/route.ts');
    assert('exec-tokens: auth route binds device on first use', /lockedDeviceId:\s*dev/.test(authRoute));
    assert('exec-tokens: auth route rejects second device (403)', /403/.test(authRoute) && /already in use on another device/.test(authRoute));

    const tokensRoute = read('src/app/api/executive/tokens/route.ts');
    assert('exec-tokens: generation is ADMIN-only', /role.*!==.*'ADMIN'|'ADMIN'/.test(tokensRoute) && /Admin access required/.test(tokensRoute));
    assert('exec-tokens: tokens stored hashed (never plaintext)', /hashExecToken/.test(tokensRoute) && /tokenHash/.test(tokensRoute));
    assert('exec-tokens: full token returned only once (fullToken)', /fullToken/.test(tokensRoute));

    // 4. Metrics route honors the display token.
    const reports = read('src/app/api/reports/executive/route.ts');
    assert('exec-tokens: /api/reports/executive authorizes via display token', /getExecutiveDisplaySession/.test(reports));
    assert('exec-tokens: /api/reports/executive returns full shape (monitors + recentAlerts)', /monitors:\s*monitorsOut/.test(reports) && /recentAlerts,/.test(reports));

    // 5. Client gate.
    const layout = read('src/app/executive/layout.tsx');
    assert('exec-tokens: /executive layout gated by ExecutiveAuthWrapper', /ExecutiveAuthWrapper/.test(layout));

    ok('audit3-executive-display-tokens', 'login-less executive dashboard secured by admin-minted, device-locked tokens');
}

main();
