/**
 * PR-36 / EA-5 smoke — Playwright spec exists and asserts the
 * security-critical contract from the 2026-05-22 due-diligence review:
 * a session JWT issued before a 2FA disable must NOT authenticate
 * subsequent requests.
 *
 * The runtime test itself depends on a seeded TOTP fixture user that
 * doesn't ship with the repo today (test.fixme'd by default). This
 * smoke gates the spec FILE so it can't be silently deleted or
 * gutted, even while the fixture is missing.
 */
import './_lib';
import { ok, fail } from './_lib';
import { readFileSync, existsSync } from 'fs';
import path from 'path';

const SPEC = path.resolve(__dirname, '../../src/e2e/e2e/2fa-disable-jwt-rejection.spec.ts');

function main(): void {
    if (!existsSync(SPEC)) fail('ea-5: spec file missing', SPEC);
    const src = readFileSync(SPEC, 'utf8');

    // 1. Spec captures the OLD cookie and re-attaches it in a new context
    if (!/sessionCookie\s*=.*cookies\.find/.test(src)) {
        fail('ea-5: spec does not capture the session cookie', 'OLD-cookie capture missing');
    }
    if (!/ctxB\.addCookies\(\[sessionCookie/.test(src)) {
        fail('ea-5: spec does not replay the OLD cookie in a new context', 'replay step missing');
    }
    ok('ea-5: spec captures + replays the pre-disable cookie');

    // 2. The disable flow is exercised (settings page + Disable button)
    if (!/\/settings\?tab=security/.test(src)) {
        fail('ea-5: spec does not navigate to the 2FA settings tab', 'disable step missing');
    }
    if (!/Disable 2FA/.test(src)) {
        fail('ea-5: spec does not click the Disable 2FA confirmation', 'disable step missing');
    }
    ok('ea-5: spec exercises the 2FA disable flow');

    // 3. Assertion is on a rejection status (401/302/307)
    if (!/toContain\(status\)/.test(src) && !/expect\(\[401/.test(src)) {
        fail('ea-5: spec does not assert rejection status', 'security-critical assertion missing');
    }
    if (!/\b401\b/.test(src) || !/\b302\b/.test(src) || !/\b307\b/.test(src)) {
        fail('ea-5: spec does not cover all expected rejection statuses (401/302/307)', 'partial assertion');
    }
    ok('ea-5: spec asserts rejection on OLD cookie replay');

    // 4. The test is fixme'd with a clear reason (the fixture user is
    //    not seeded by the repo today). Acceptable; the smoke runs even
    //    when the spec is skipped — what we're protecting is the contract.
    if (!/test\.fixme\(/.test(src)) {
        fail('ea-5: spec is not test.fixme-skipped despite missing fixture', 'will fail in CI');
    }
    if (!/seeded TOTP fixture/i.test(src)) {
        fail('ea-5: spec does not document why it is fixme-skipped', 'context missing');
    }
    ok('ea-5: spec is fixme-skipped pending fixture seed, documented reason');

    ok('PR-36 2FA runtime test', 'spec contract is guarded; fixme until fixture lands');
}

main();
