import { describe, it, expect } from 'vitest';
import { spawnSync } from 'node:child_process';
import { resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { dirname } from 'node:path';

// The capture script is a local-only utility (never invoked from CI) but its
// failure modes are load-bearing for the canonical fixture lifecycle: a slip
// in env vars must not silently authenticate to a non-local backend or
// overwrite the canonical snapshot with a vacuous response. These guards are
// the public contract.

const HERE = dirname(fileURLToPath(import.meta.url));
const SCRIPT_PATH = resolve(HERE, '../../../../../scripts/capture-network-fixture.mjs');

function runScript(env: Record<string, string | undefined>) {
	return spawnSync(process.execPath, [SCRIPT_PATH], {
		env: { PATH: process.env.PATH, ...env } as NodeJS.ProcessEnv,
		encoding: 'utf8',
		timeout: 5_000
	});
}

describe('capture-network-fixture.mjs — preflight guards', () => {
	it('refuses_to_run_without_explicit_CAPTURE_EMAIL', () => {
		const result = runScript({
			CAPTURE_PASSWORD: 'pw',
			BACKEND_URL: 'http://localhost:8080'
		});
		expect(result.status).not.toBe(0);
		expect(result.stderr).toMatch(/CAPTURE_EMAIL/);
	});

	it('refuses_to_run_without_explicit_CAPTURE_PASSWORD', () => {
		const result = runScript({
			CAPTURE_EMAIL: 'someone@example.test',
			BACKEND_URL: 'http://localhost:8080'
		});
		expect(result.status).not.toBe(0);
		expect(result.stderr).toMatch(/CAPTURE_PASSWORD/);
	});

	it('refuses_to_run_when_BACKEND_URL_is_not_localhost', () => {
		const result = runScript({
			CAPTURE_EMAIL: 'someone@example.test',
			CAPTURE_PASSWORD: 'pw',
			BACKEND_URL: 'https://staging.example.com'
		});
		expect(result.status).not.toBe(0);
		expect(result.stderr).toMatch(/BACKEND_URL/);
		expect(result.stderr).toMatch(/localhost|127\.0\.0\.1/);
	});

	it('accepts_127_0_0_1_as_BACKEND_URL', () => {
		// With creds + a localhost backend the preflight passes; the fetch
		// then fails (no server) — but the exit message must NOT mention the
		// preflight guards, proving they let the run through.
		const result = runScript({
			CAPTURE_EMAIL: 'someone@example.test',
			CAPTURE_PASSWORD: 'pw',
			BACKEND_URL: 'http://127.0.0.1:65500'
		});
		expect(result.stderr).not.toMatch(/BACKEND_URL.*localhost/);
		expect(result.stderr).not.toMatch(/CAPTURE_EMAIL/);
		expect(result.stderr).not.toMatch(/CAPTURE_PASSWORD/);
	});
});
