/**
 * P2-10 smoke test — /api/health/deep returns aggregated check status.
 *
 * Run: npx tsx scripts/smoke/p2-10-deep-health.ts
 *
 * Drives the GET handler directly with mocked prisma so no live DB is
 * required.
 */
import './_lib';
import { ok, fail } from './_lib';

const prismaMod = require('../../src/lib/prisma') as { prisma: Record<string, unknown> };
prismaMod.prisma.$queryRaw = async () => [{ 1: 1 }];
prismaMod.prisma.monitor = {
    findFirst: async () => ({ lastCheckAt: new Date(Date.now() - 30_000) }),
} as unknown;
prismaMod.prisma.notificationOutbox = {
    count: async () => 0,
} as unknown;

delete process.env.SMTP_HOST;
delete process.env.SMTP_PORT;

// PR-B.4: GET requires Authorization: Bearer CRON_SECRET.
process.env.CRON_SECRET = 'this-is-a-long-enough-secret-1';
const authedReq = {
    url: 'http://localhost:3000/api/health/deep',
    headers: {
        get: (k: string) => (k.toLowerCase() === 'authorization' ? `Bearer ${process.env.CRON_SECRET}` : null),
    },
} as never;

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

async function main(): Promise<void> {
    const res = await GET(authedReq);
    if (res.status !== 200) fail('P2-10 healthy path', `expected 200, got ${res.status}`);
    const body = (await res.json()) as { status: string; checks: Array<{ name: string; ok: boolean }> };
    if (body.status !== 'healthy') fail('P2-10 status', `expected healthy, got ${body.status}`);
    ok('Healthy state returns 200');

    const names = body.checks.map((c) => c.name).sort();
    const expected = ['db', 'outbox', 'smtp', 'worker'];
    for (const n of expected) {
        if (!names.includes(n)) fail('P2-10 coverage', `check missing: ${n}`);
    }
    ok(`All required checks present: ${names.join(', ')}`);

    // Degrade by making the worker stale.
    prismaMod.prisma.monitor = {
        findFirst: async () => ({ lastCheckAt: new Date(Date.now() - 30 * 60 * 1000) }),
    } as unknown;
    const res2 = await GET(authedReq);
    if (res2.status !== 503) fail('P2-10 stale-worker', `expected 503, got ${res2.status}`);
    ok('Stale worker → 503');

    ok('P2-10 deep-health', '/api/health/deep proves DB + worker + outbox + SMTP');
}

main().catch((err) => fail('P2-10 deep-health', String(err)));
