import { defineConfig } from '@playwright/test';
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { fileURLToPath } from 'node:url';

// Load .dev.vars into process.env so test workers can read SEED_ADMIN_EMAIL / SEED_ADMIN_PASSWORD.
// Playwright passes process.env from the config module to all worker processes, so loading here
// makes credentials available in theme-public.spec.ts without hardcoding the dev DB admin.
try {
  const dir = resolve(fileURLToPath(import.meta.url), '..');
  const raw = readFileSync(resolve(dir, '.dev.vars'), 'utf-8');
  for (const line of raw.split('\n')) {
    const eq = line.indexOf('=');
    if (eq > 0) {
      const key = line.slice(0, eq).trim();
      if (/^[A-Z0-9_]+$/.test(key)) process.env[key] ??= line.slice(eq + 1).trim();
    }
  }
} catch { /* .dev.vars absent — tests fall back to install-appearance hardcoded credentials */ }

process.env.MOD_CMS_TRANSLATION_MOCK ??= '1';

// Ops-gated admin e2e (runsheet Task 6b). Runs against `astro dev`, NOT `preview`: the Cloudflare
// adapter's platformProxy is default-on in dev and reads `.dev.vars` + wrangler.toml into
// `locals.runtime.env` — the only path that gives the admin routes their DATABASE_URL / auth secrets
// locally. `.dev.vars` must point at a real (throwaway) Neon branch with auth schema + a seeded admin.
// SITE_ORIGIN in `.dev.vars` MUST equal baseURL so same-origin CSRF passes on session mutations.
export default defineConfig({
  testDir: './e2e',
  testMatch: '**/*.spec.ts',
  // Session cookies are Secure; serial run keeps the single seeded admin's session deterministic.
  workers: 1,
  use: {
    // Dedicated port: 4321 may be occupied by another app's dev server. reuseExistingServer:false
    // forces a fresh mod-cms dev server so the e2e never latches onto a foreign app. SITE_ORIGIN in
    // .dev.vars MUST equal this baseURL or same-origin CSRF rejects every session mutation.
    baseURL: 'http://localhost:4331',
  },
  webServer: {
    command: 'pnpm --filter @app/mod-cms dev --port 4331',
    url: 'http://localhost:4331',
    reuseExistingServer: false,
    timeout: 120_000,
  },
});
