import path from 'node:path'
import { fileURLToPath } from 'node:url'

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

const mockBaseUrl = 'http://127.0.0.1:5159'
const frontendBaseUrl = 'http://127.0.0.1:4321'
const adminBaseUrl = 'http://127.0.0.1:4322'
const isCi = Boolean(process.env.CI)
const useBuiltApp = process.env.PLAYWRIGHT_USE_BUILT_APP === '1'
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
const repoRoot = path.resolve(__dirname, '..')
const frontendCommand = useBuiltApp
  ? 'node ./dist/server/entry.mjs'
  : 'pnpm dev --host 127.0.0.1 --port 4321'
const adminCommand = useBuiltApp
  ? 'pnpm preview --host 127.0.0.1 --port 4322'
  : 'pnpm dev --host 127.0.0.1 --port 4322'

export default defineConfig({
  testDir: './tests',
  fullyParallel: false,
  workers: 1,
  timeout: 60_000,
  expect: {
    timeout: 12_000,
  },
  reporter: [['list'], ['html', { open: 'never' }]],
  use: {
    trace: 'on-first-retry',
    screenshot: 'only-on-failure',
    video: 'retain-on-failure',
    headless: true,
  },
  projects: [
    {
      name: 'frontend',
      testMatch: /frontend\.spec\.ts/,
      use: {
        ...devices['Desktop Chrome'],
        channel: isCi ? undefined : 'msedge',
        baseURL: frontendBaseUrl,
      },
    },
    {
      name: 'admin',
      testMatch: /admin\.spec\.ts/,
      use: {
        ...devices['Desktop Chrome'],
        channel: isCi ? undefined : 'msedge',
        baseURL: adminBaseUrl,
      },
    },
  ],
  webServer: [
    {
      command: 'node ./mock-server.mjs',
      cwd: __dirname,
      url: `${mockBaseUrl}/__playwright/health`,
      reuseExistingServer: !isCi,
      stdout: 'pipe',
      stderr: 'pipe',
      env: {
        ...process.env,
        PLAYWRIGHT_MOCK_PORT: '5159',
        PLAYWRIGHT_FRONTEND_ORIGIN: frontendBaseUrl,
        PLAYWRIGHT_ADMIN_ORIGIN: adminBaseUrl,
      },
    },
    {
      command: frontendCommand,
      cwd: path.resolve(repoRoot, 'frontend'),
      url: frontendBaseUrl,
      reuseExistingServer: !isCi,
      stdout: 'pipe',
      stderr: 'pipe',
      env: {
        ...process.env,
        HOST: '127.0.0.1',
        PORT: '4321',
        ...(useBuiltApp ? { NODE_ENV: 'production' } : {}),
        PUBLIC_API_BASE_URL: `${mockBaseUrl}/api`,
        INTERNAL_API_BASE_URL: `${mockBaseUrl}/api`,
        PUBLIC_IMAGE_ALLOWED_HOSTS: '127.0.0.1:5159,127.0.0.1',
      },
    },
    {
      command: adminCommand,
      cwd: path.resolve(repoRoot, 'admin'),
      url: adminBaseUrl,
      reuseExistingServer: !isCi,
      stdout: 'pipe',
      stderr: 'pipe',
      env: {
        ...process.env,
        VITE_API_BASE: mockBaseUrl,
        VITE_FRONTEND_BASE_URL: frontendBaseUrl,
      },
    },
  ],
})
