/**
 * Playwright global setup — health check for Keycloak + SvelteKit dev server.
 *
 * Auth state is NOT cached across tests: each test calls `loginAs(page, user)`
 * to perform the full Keycloak login. This is slower but deterministic. Previous
 * iterations used `browser.newContext({ storageState })`, but Supabase JS v2's
 * async `_recoverAndRefresh` doesn't reliably re-fire INITIAL_SESSION on restore.
 */
import type { FullConfig } from '@playwright/test';

const KEYCLOAK_URL = process.env.PUBLIC_KEYCLOAK_URL ?? 'http://localhost:8080';
const KEYCLOAK_REALM = process.env.PUBLIC_KEYCLOAK_REALM ?? 'colectivo';

export default async function globalSetup(_config: FullConfig) {
	// Minimal health check: Keycloak realm discovery endpoint is reachable.
	try {
		const res = await fetch(
			`${KEYCLOAK_URL}/realms/${KEYCLOAK_REALM}/.well-known/openid-configuration`,
			{ signal: AbortSignal.timeout(5_000) }
		);
		if (!res.ok) {
			throw new Error(`Keycloak realm discovery returned ${res.status}`);
		}
	} catch (err) {
		throw new Error(
			`Keycloak not reachable at ${KEYCLOAK_URL} — is \`just dev\` running? ${err}`
		);
	}
}
