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

const API_URL = process.env.PLAYWRIGHT_API_URL ?? 'http://127.0.0.1:8000';
const ADMIN_URL = process.env.PLAYWRIGHT_ADMIN_URL ?? 'http://localhost:3801';
const FRONT_URL = process.env.PLAYWRIGHT_FRONT_URL ?? 'http://localhost:3800';
const ARTIFACT_DIR = 'artifacts';

/** 默认用本机 Google Chrome；设 PLAYWRIGHT_USE_BUNDLED_CHROMIUM=1 则走 ms-playwright 自带 Chromium。 */
const uiBrowserUse = {
  ...devices['Desktop Chrome'],
  ...(process.env.PLAYWRIGHT_USE_BUNDLED_CHROMIUM === '1'
    ? {}
    : { channel: 'chrome' as const }),
};

export default defineConfig({
  testDir: './tests',
  globalSetup: './global-setup.ts',
  fullyParallel: false,
  workers: 1,
  forbidOnly: !!process.env.CI,
  retries: process.env.CI ? 1 : 0,
  reporter: [
    ['list'],
    ['json', { outputFile: `${ARTIFACT_DIR}/test-results/results.json` }],
    ['html', { outputFolder: `${ARTIFACT_DIR}/playwright-report`, open: 'never' }],
  ],
  outputDir: `${ARTIFACT_DIR}/test-output`,
  timeout: 60_000,
  expect: { timeout: 10_000 },
  use: {
    trace: 'retain-on-failure',
    screenshot: 'only-on-failure',
    video: 'retain-on-failure',
  },
  projects: [
    {
      name: 'api',
      testMatch: 'tests/api/**/*.spec.ts',
      use: {
        baseURL: API_URL,
        extraHTTPHeaders: { 'Accept-Language': 'zh-CN' },
        ...devices['Desktop Chrome'],
      },
    },
    {
      name: 'admin-ui',
      testMatch: 'tests/ui/admin*.spec.ts',
      use: {
        baseURL: ADMIN_URL,
        ...uiBrowserUse,
      },
    },
    {
      name: 'front-ui',
      testMatch: 'tests/ui/front*.spec.ts',
      use: {
        baseURL: FRONT_URL,
        ...uiBrowserUse,
      },
    },
  ],
});
