/**
 * Shared helpers for Phase 0 smoke scripts.
 *
 * Each smoke script imports these to:
 *  - Print structured OK/FAIL lines.
 *  - Hit the local dev server (assumed running on http://localhost:3005).
 *  - Bail with a non-zero exit code on failure so CI can chain them.
 *
 * Side effect: populates the env vars src/lib/env.ts requires (P0-8 now
 * fails fast on missing secrets). Smoke scripts that import library code
 * transitively load env.ts; without these placeholders they'd never run
 * standalone.
 */
import crypto from 'crypto';

if (!process.env.DATABASE_URL) {
    process.env.DATABASE_URL = 'mysql://smoke:smoke@localhost:3306/uptime_sentinel_smoke';
}
if (!process.env.NEXTAUTH_SECRET) {
    process.env.NEXTAUTH_SECRET = 'smoke-secret-' + crypto.randomBytes(16).toString('hex');
}
if (!process.env.NEXTAUTH_URL) {
    process.env.NEXTAUTH_URL = 'http://localhost:3005';
}
if (!process.env.CHANNEL_ENCRYPTION_KEY) {
    process.env.CHANNEL_ENCRYPTION_KEY = crypto.randomBytes(32).toString('base64');
}

export const BASE_URL = process.env.SMOKE_BASE_URL ?? 'http://localhost:3005';

export function ok(name: string, detail?: string): void {
    const suffix = detail ? ` — ${detail}` : '';
    console.log(`OK: ${name}${suffix}`);
}

export function fail(name: string, detail: string): never {
    console.error(`FAIL: ${name} — ${detail}`);
    process.exit(1);
}

export async function expectStatus(
    label: string,
    res: Response,
    expected: number | number[]
): Promise<void> {
    const list = Array.isArray(expected) ? expected : [expected];
    if (list.includes(res.status)) {
        ok(label, `status ${res.status}`);
        return;
    }
    let body = '';
    try {
        body = (await res.text()).slice(0, 200);
    } catch {
        body = '<no body>';
    }
    fail(label, `expected ${list.join('|')}, got ${res.status}. Body: ${body}`);
}
