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

const BASE_URL = 'http://localhost:3000';
const FRONTEND_URL = process.env.FRONTEND_URL || 'http://localhost:5173';

export default defineConfig({
  // 测试目录（项目根 tests/ 下）
  testDir: '.',

  // 全局超时
  timeout: 120000,
  expect: { timeout: 15000 },

  // 失败重试
  retries: process.env.CI ? 1 : 0,

  // 并行数
  workers: process.env.CI ? 2 : 1,

  // 报告配置（含 AI 可读的 Markdown 摘要）
  reporter: [
    ['list'],
    ['json', { outputFile: 'test-results/results.json' }],
    ['html', { outputFolder: 'test-results/report', open: 'never' }],
    ['./helpers/reporter.ts'],
  ],

  // 全局设置
  use: {
    baseURL: BASE_URL,
    trace: 'retain-on-failure',
    screenshot: 'on',
    video: 'retain-on-failure',
  },

  // 项目配置：冒烟测试 & 回归测试 & 关键旅程
  projects: [
    {
      name: 'smoke',
      testDir: './smoke',
      use: { ...devices['Desktop Chrome'] },
    },
    {
      name: 'regression',
      testDir: './regression',
      use: { ...devices['Desktop Chrome'] },
    },
    {
      name: 'critical-journeys',
      testDir: './e2e/ui/critical-journeys',
      use: { ...devices['Desktop Chrome'] },
    },
  ],

  // 全局 setup / teardown
  globalSetup: './global-setup.ts',
  globalTeardown: './global-teardown.ts',

  // Web 服务器（可选，也可手动启动）
  webServer: process.env.START_SERVER
    ? [
        {
          command: 'npx tsx server/src/app.ts',
          port: 3000,
          timeout: 30000,
          reuseExistingServer: true,
        },
        {
          command: 'npm run dev:h5',
          cwd: 'my-uniapp-vue3',
          port: 5173,
          timeout: 30000,
          reuseExistingServer: true,
        },
      ]
    : undefined,
});
