/**
 * P0-8 smoke test — env.ts refuses to start with missing/short secrets.
 *
 * Run: npx tsx scripts/smoke/p0-8-env-strict.ts
 *
 * Forks subprocesses (via scripts/smoke/_env-strict-child.ts) with
 * controlled env to confirm the validator actually exits non-zero, vs.
 * the previous silent partial-env fallback.
 */
import { spawnSync } from 'child_process';
import path from 'path';
import crypto from 'crypto';
import { ok, fail } from './_lib';

const CHILD = path.resolve(__dirname, '_env-strict-child.ts');

function run(envOverride: Record<string, string | undefined>, label: string, wantOk: boolean): void {
    const env: NodeJS.ProcessEnv = { ...process.env };
    for (const [k, v] of Object.entries(envOverride)) {
        if (v === undefined) delete env[k];
        else env[k] = v;
    }

    // Quote the path to survive spaces on Windows; shell:true requires
    // string command + quoted args.
    const result = spawnSync(`npx tsx "${CHILD}"`, {
        env,
        encoding: 'utf8',
        shell: true,
    });

    const startedOk = (result.stdout || '').includes('STARTED_OK');
    if (wantOk && !startedOk) {
        fail(label, `expected clean start, stderr=${(result.stderr || '').slice(0, 400)}, stdout=${(result.stdout || '').slice(0, 200)}`);
    }
    if (!wantOk && startedOk) {
        fail(label, `expected validator to throw, but startup succeeded`);
    }
    ok(label);
}

function main(): void {
    const goodSecret = 'this-is-a-long-enough-secret-1234567890';
    const goodKey = crypto.randomBytes(32).toString('base64');

    const base = {
        NODE_ENV: 'development',
        DATABASE_URL: 'mysql://x:y@localhost:3306/db',
        NEXTAUTH_URL: 'http://localhost:3005',
        NEXTAUTH_SECRET: goodSecret,
        CHANNEL_ENCRYPTION_KEY: goodKey,
    };

    run({ ...base, NEXTAUTH_SECRET: undefined }, 'Missing NEXTAUTH_SECRET → rejects', false);
    run({ ...base, CHANNEL_ENCRYPTION_KEY: undefined }, 'Missing CHANNEL_ENCRYPTION_KEY → rejects', false);
    run({ ...base, NEXTAUTH_SECRET: 'too-short' }, 'NEXTAUTH_SECRET too short → rejects', false);
    run({ ...base, CHANNEL_ENCRYPTION_KEY: 'short' }, 'CHANNEL_ENCRYPTION_KEY too short → rejects', false);
    run({ ...base }, 'All required vars present → starts cleanly', true);

    ok('P0-8 env-strict', 'validator refuses missing/short secrets, accepts valid set');
}

main();
