/**
 * audit3-followup smoke — route-test coverage floor.
 *
 * Run: npx tsx scripts/smoke/audit3-route-test-coverage.ts
 *
 * Why this exists (2026-05-29):
 *   Pre-audit3, only 5 of 75 route.ts files had jest coverage (6.7%).
 *   This PR added 3 more (cron auth, health, metrics) — bringing the
 *   total to 8 (10.7%). The smoke asserts the floor never drops below
 *   this number, so a future contributor can't silently delete tests.
 *
 *   The real goal — ~30% coverage — is incremental. Each future PR
 *   that lands a new route should add a matching test; the floor
 *   ratchets up naturally over time. The smoke ratchet here is the
 *   guardrail against regressions, not the only forcing function.
 */
import './_lib';
import { ok, fail } from './_lib';
import fs from 'fs';
import path from 'path';

const ROOT = path.resolve(__dirname, '../..');
const MIN_ROUTE_TESTS = 8;
const MIN_COVERAGE_PCT = 10;

function listRouteFiles(dir: string, out: string[] = []): string[] {
    for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
        const full = path.join(dir, entry.name);
        if (entry.isDirectory()) listRouteFiles(full, out);
        else if (entry.name === 'route.ts') out.push(full);
    }
    return out;
}

function listRouteTests(dir: string, out: string[] = []): string[] {
    for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
        const full = path.join(dir, entry.name);
        if (entry.isDirectory()) listRouteTests(full, out);
        else if (entry.name.endsWith('.test.ts')) out.push(full);
    }
    return out;
}

function main(): void {
    const apiDir = path.join(ROOT, 'src/app/api');
    const routes = listRouteFiles(apiDir);
    const tests = listRouteTests(apiDir);

    if (tests.length < MIN_ROUTE_TESTS) {
        fail(
            'audit3-route-coverage: floor breached',
            `Found ${tests.length} route test file(s) under src/app/api/ — must be ≥${MIN_ROUTE_TESTS}. ` +
            `Did someone delete tests? The audit3-followup PR established this floor.`,
        );
    }
    ok(`${tests.length} route test file(s) under src/app/api/ (floor: ${MIN_ROUTE_TESTS})`);

    const coverage = Math.floor((tests.length / routes.length) * 100);
    if (coverage < MIN_COVERAGE_PCT) {
        fail(
            'audit3-route-coverage: percentage dropped',
            `Route-test coverage is ${coverage}% (${tests.length}/${routes.length}); minimum is ${MIN_COVERAGE_PCT}%.`,
        );
    }
    ok(`route-test coverage: ${coverage}% (${tests.length}/${routes.length}) — minimum is ${MIN_COVERAGE_PCT}%`);

    ok('audit3-route-coverage', 'route-test count + percentage floor both intact');
}

main();
