/**
 * PR-B.4 smoke — /api/health/deep enforces Authorization: Bearer
 * CRON_SECRET so unauth requests can't enumerate operational signals.
 *
 * Run: npx tsx scripts/smoke/prb-4-health-probe-auth.ts
 */
import './_lib';
import { ok, fail } from './_lib';

// Stub Prisma + Net at module init so the route's GET handler doesn't
// reach a live DB. Net is stubbed via the global net module mock below.
const prismaMod = require('../../src/lib/prisma') as { prisma: Record<string, unknown> };
prismaMod.prisma.$queryRaw = (async () => 1) as never;
prismaMod.prisma.monitor = {
    findFirst: (async () => ({ lastCheckAt: new Date() })) as never,
};
prismaMod.prisma.notificationOutbox = {
    count: (async () => 0) as never,
};

async function main(): Promise<void> {
    // Stub SMTP_HOST/PORT to skip the net.connect path.
    delete process.env.SMTP_HOST;
    delete process.env.SMTP_PORT;
    process.env.CRON_SECRET = 'this-is-a-long-enough-secret-1';

    const { GET } = await import('../../src/app/api/health/deep/route');

    // Helper that builds a NextRequest-shaped object that requireCronSecret accepts.
    const makeReq = (auth?: string): {
        url: string;
        headers: { get: (k: string) => string | null };
    } => ({
        url: 'http://localhost:3000/api/health/deep',
        headers: {
            get: (k: string) => (k.toLowerCase() === 'authorization' && auth) ? auth : null,
        },
    });

    // Case 1: no auth header -> 401.
    const r1 = await GET(makeReq() as never);
    if (r1.status !== 401) fail('PR-B.4 no-auth', `expected 401, got ${r1.status}`);
    ok('GET /api/health/deep without Authorization -> 401');

    // Case 2: wrong secret -> 401.
    const r2 = await GET(makeReq('Bearer wrong-secret') as never);
    if (r2.status !== 401) fail('PR-B.4 wrong-secret', `expected 401, got ${r2.status}`);
    ok('GET /api/health/deep with wrong Bearer -> 401');

    // Case 3: correct secret -> 200 (DB + worker + outbox all healthy).
    const r3 = await GET(makeReq(`Bearer ${process.env.CRON_SECRET}`) as never);
    if (r3.status !== 200) fail('PR-B.4 correct-secret', `expected 200, got ${r3.status}`);
    ok('GET /api/health/deep with correct Bearer CRON_SECRET -> 200');

    ok('PR-B.4 health-probe-auth smoke', '/api/health/deep gated behind CRON_SECRET');
}

main().catch((e) => fail('PR-B.4 crashed', String(e)));
