import fs from 'node:fs';
import path from 'node:path';
import { defineConfig, devices } from '@playwright/test';

/** Read a key from monorepo root `.env` when not set in the shell (Docker custom ports). */
function readEnvFile(key: string): string | undefined {
  try {
    const envPath = path.join(__dirname, '.env');
    const text = fs.readFileSync(envPath, 'utf8');
    for (const line of text.split(/\r?\n/)) {
      const trimmed = line.trim();
      if (!trimmed || trimmed.startsWith('#')) continue;
      const eq = trimmed.indexOf('=');
      if (eq < 1) continue;
      const k = trimmed.slice(0, eq).trim();
      if (k !== key) continue;
      const v = trimmed.slice(eq + 1).trim().replace(/^["']|["']$/g, '');
      return v || undefined;
    }
  } catch {
    /* no .env */
  }
  return undefined;
}

const frontendPort = process.env.FRONTEND_PORT?.trim() || readEnvFile('FRONTEND_PORT') || '3000';
const apiPort = process.env.API_HOST_PORT?.trim() || readEnvFile('API_HOST_PORT') || '3001';
const defaultBase = `http://localhost:${frontendPort}`;

// Propagate for e2e helpers (smoke.spec API login)
process.env.PLAYWRIGHT_API_URL ??= `http://localhost:${apiPort}`;

/**
 * E2E smoke tests — run against a live stack (e.g. docker compose).
 * Default base URL: http://localhost:$FRONTEND_PORT (3000 if unset). Override with PLAYWRIGHT_BASE_URL.
 */
export default defineConfig({
  testDir: 'e2e',
  fullyParallel: true,
  forbidOnly: !!process.env.CI,
  retries: process.env.CI ? 2 : 0,
  workers: process.env.CI ? 1 : undefined,
  reporter: 'list',
  use: {
    baseURL: process.env.PLAYWRIGHT_BASE_URL ?? defaultBase,
    trace: 'on-first-retry',
    ...devices['Desktop Chrome'],
  },
});
