/**
 * P0-1 smoke test — every /api/cron/* endpoint requires CRON_SECRET.
 *
 * Run: npx tsx scripts/smoke/p0-1-cron-auth.ts
 * Pre-req: dev server running on http://localhost:3005 with CRON_SECRET set
 *          to a value ≥ 16 chars. Override server URL with SMOKE_BASE_URL.
 */
import { BASE_URL, expectStatus, ok, fail } from './_lib';

const ROUTES = [
    '/api/cron',
    '/api/cron/cleanup',
    '/api/cron/run-checks',
];

async function main(): Promise<void> {
    const secret = process.env.CRON_SECRET;
    if (!secret) {
        fail(
            'P0-1 preflight',
            'CRON_SECRET is not set in this shell. Export it so the smoke test can call the authed path.'
        );
    }

    for (const path of ROUTES) {
        // 1. No secret → 401
        const noSecret = await fetch(`${BASE_URL}${path}`);
        await expectStatus(`${path} without secret`, noSecret, 401);

        // 2. Wrong secret → 401
        const wrong = await fetch(`${BASE_URL}${path}?secret=wrong-value-1234567`);
        await expectStatus(`${path} with wrong secret`, wrong, 401);

        // 3. Correct secret → 200 / 409 (mode skip) / 503 are all acceptable
        //    "OK auth, may short-circuit on mode" is the relevant signal.
        const right = await fetch(`${BASE_URL}${path}?secret=${encodeURIComponent(secret!)}`);
        await expectStatus(`${path} with correct secret`, right, [200, 409, 500]);
    }

    ok('P0-1 cron-auth', `all ${ROUTES.length} routes enforce CRON_SECRET`);
}

main().catch((err) => fail('P0-1 cron-auth', String(err)));
