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

/**
 * Playwright E2E 測試配置
 * =======================
 * Phase VI: 截圖 + 錄影自動產出
 * Wave 4: ignoreHTTPSErrors + Visual Baseline (2026-03-31)
 */

// Phase 20: 支持環境變數覆蓋 baseURL，可針對生產環境測試
const baseURL = process.env.PLAYWRIGHT_BASE_URL || 'http://localhost:3000'
const isRemote = baseURL !== 'http://localhost:3000'

export default defineConfig({
  // Wave 4: Global Setup for Auth Bypass
  globalSetup: './tests/e2e/global.setup.ts',

  testDir: './tests/e2e',
  fullyParallel: true,
  forbidOnly: !!process.env.CI,
  retries: process.env.CI ? 2 : 0,
  workers: process.env.CI ? 1 : undefined,
  reporter: [
    ['html', { outputFolder: 'test-results/html-report' }],
    ['list'],
  ],

  use: {
    // Base URL for navigation (可通過 PLAYWRIGHT_BASE_URL 環境變數覆蓋)
    baseURL,

    // Wave 4: HTTPS 錯誤忽略 (自簽憑證環境)
    ignoreHTTPSErrors: true,

    // 截圖與錄影 - 統帥強制要求
    // 2026-04-16 ogt: CI 遠端 smoke test 改為 retain-on-failure，避免錄影拖慢 13min+ → ~1min
    screenshot: isRemote ? 'only-on-failure' : 'on',
    video: isRemote ? 'retain-on-failure' : 'on',
    trace: 'on-first-retry',

    // Viewport - Wave 4: deviceScaleFactor 固定為 1 (Visual Baseline 一致性)
    viewport: { width: 1920, height: 1080 },
    deviceScaleFactor: 1,

    // Timeouts
    actionTimeout: 10000,
    navigationTimeout: 30000,
  },

  // Wave 4: Visual Regression 比對容差 (5%)
  expect: {
    toHaveScreenshot: {
      maxDiffPixelRatio: 0.05,
    },
  },

  // Output directory for screenshots and videos
  outputDir: 'test-results',

  projects: [
    {
      name: 'chromium',
      use: { ...devices['Desktop Chrome'] },
    },
  ],

  // Web server configuration - start Next.js dev server
  // 當使用遠端 URL (PLAYWRIGHT_BASE_URL) 時跳過本地 dev server
  ...(isRemote ? {} : {
    webServer: {
      command: 'pnpm dev',
      url: 'http://localhost:3000',
      reuseExistingServer: !process.env.CI,
      timeout: 120000,
    },
  }),
})
