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

function parseEnvFile(content: string): Record<string, string> {
  const vars: Record<string, string> = {};
  for (const line of content.split('\n')) {
    const trimmed = line.trim();
    if (!trimmed || trimmed.startsWith('#')) continue;
    const index = trimmed.indexOf('=');
    if (index === -1) continue;
    vars[trimmed.slice(0, index).trim()] = trimmed
      .slice(index + 1)
      .trim()
      .replace(/^["']|["']$/g, '');
  }
  return vars;
}

function loadEnvFile(path: string): Record<string, string> {
  if (!existsSync(path)) return {};
  return parseEnvFile(readFileSync(path, 'utf8'));
}

const configDir = new URL('.', import.meta.url).pathname;
Object.assign(process.env, loadEnvFile(join(configDir, '.env')));
Object.assign(process.env, loadEnvFile(join(configDir, '.dev.vars')));
const uiPort = Number(process.env.UI_PORT ?? 4321);
// Force the local preview server — .dev.vars carries BASE_URL=https://dev.multi.deal,
// which would silently point the suite at the deployed worker instead of the build under test.
process.env.BASE_URL = `http://127.0.0.1:${uiPort}`;

export default defineConfig({
  testDir: './tests/e2e/ui-overhaul',
  fullyParallel: false,
  forbidOnly: true,
  retries: 0,
  // Suite shares the machine with builds/CI of other checkouts; the default
  // 30s test timeout produces false negatives under load.
  timeout: 60000,
  // Single worker: the CPU-quota'd preview worker 503s island/API requests
  // under parallel load, emptying the gallery page.
  workers: 1,
  reporter: 'line',
  outputDir: 'test-results/ui-overhaul',
  use: {
    baseURL: process.env.BASE_URL,
    serviceWorkers: 'block',
    trace: 'on-first-retry',
    screenshot: 'only-on-failure',
    video: 'on',
    locale: 'he-IL',
    timezoneId: 'Asia/Jerusalem',
  },
  projects: [{ name: 'ui-overhaul', use: { ...devices['Desktop Chrome'] } }],
  webServer: {
    command: `pnpm build && pnpm preview --host 127.0.0.1 --port ${uiPort}`,
    port: uiPort,
    reuseExistingServer: false,
    timeout: 600000,
  },
});
