import { defineConfig, devices } from '@playwright/test'

/**
 * Read environment variables from file.
 * https://github.com/motdotla/dotenv
 */
import 'dotenv/config'

// Use port 3001 for tests to avoid conflicts with PM2 on 3000
const TEST_PORT = process.env.TEST_PORT || '3001'
const TEST_URL = `http://localhost:${TEST_PORT}`

/**
 * Playwright E2E Test Configuration
 *
 * Tests critical flows:
 * - Authentication (login, CSRF)
 * - News API (tenant isolation, filtering)
 * - Newsletter (Double Opt-In flow)
 * - Form submissions
 * - Tenant data isolation
 *
 * See https://playwright.dev/docs/test-configuration.
 */
export default defineConfig({
  testDir: './tests/e2e',
  /* Global test timeout */
  timeout: 30000,
  /* Expect timeout for assertions */
  expect: {
    timeout: 10000,
  },
  /* Fail the build on CI if you accidentally left test.only in the source code. */
  forbidOnly: !!process.env.CI,
  /* Retry on CI only */
  retries: process.env.CI ? 2 : 0,
  /* Opt out of parallel tests on CI. */
  workers: process.env.CI ? 1 : undefined,
  /* Reporter to use. See https://playwright.dev/docs/test-reporters */
  reporter: process.env.CI
    ? [['html', { open: 'never' }], ['github'], ['list']]
    : [['html', { open: 'on-failure' }]],
  /* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
  use: {
    /* Base URL to use in actions like `await page.goto('/')`. */
    baseURL: TEST_URL,

    /* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
    trace: 'on-first-retry',

    /* Screenshot on failure */
    screenshot: 'only-on-failure',

    /* Video recording on failure */
    video: 'retain-on-failure',
  },
  projects: [
    {
      name: 'chromium',
      use: { ...devices['Desktop Chrome'], channel: 'chromium' },
    },
  ],
  webServer: {
    command: `PORT=${TEST_PORT} pnpm start`,
    reuseExistingServer: !process.env.CI,
    url: TEST_URL,
    timeout: 120000,
    env: {
      ...process.env,
      PORT: TEST_PORT,
    },
  },
})
