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

/**
 * Playwright configuration for Bakery-IA E2E tests against local Kubernetes environment
 * This config is specifically for testing against Tilt-managed services
 *
 * Usage:
 *   npm run test:e2e:k8s
 *   npx playwright test --config=playwright.k8s.config.ts
 *
 * Prerequisites:
 *   - Tilt must be running (`tilt up`)
 *   - Frontend service must be accessible at http://localhost (via ingress)
 */
export default defineConfig({
  testDir: './tests',

  /* Run tests in files in parallel */
  fullyParallel: true,

  /* 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 */
  reporter: [
    ['html', { outputFolder: 'playwright-report' }],
    ['json', { outputFile: 'test-results/results.json' }],
    ['list'],
  ],

  /* Shared settings for all the projects below */
  use: {
    /* Base URL points to K8s ingress - override with PLAYWRIGHT_BASE_URL env var if needed */
    baseURL: process.env.PLAYWRIGHT_BASE_URL || 'http://localhost',

    /* Collect trace when retrying the failed test */
    trace: 'on-first-retry',

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

    /* Record video on failure */
    video: 'retain-on-failure',

    /* Maximum time each action (click, fill, etc) can take */
    actionTimeout: 10000,

    /* Increase navigation timeout for K8s environment (ingress routing may be slower) */
    navigationTimeout: 30000,
  },

  /* Configure projects for major browsers */
  projects: [
    // Setup project to authenticate once
    {
      name: 'setup',
      testMatch: /.*\.setup\.ts/,
    },

    // Desktop browsers
    {
      name: 'chromium',
      use: {
        ...devices['Desktop Chrome'],
        storageState: 'tests/.auth/user.json',
      },
      dependencies: ['setup'],
    },

    {
      name: 'firefox',
      use: {
        ...devices['Desktop Firefox'],
        storageState: 'tests/.auth/user.json',
      },
      dependencies: ['setup'],
    },

    {
      name: 'webkit',
      use: {
        ...devices['Desktop Safari'],
        storageState: 'tests/.auth/user.json',
      },
      dependencies: ['setup'],
    },

    // Mobile viewports
    {
      name: 'Mobile Chrome',
      use: {
        ...devices['Pixel 5'],
        storageState: 'tests/.auth/user.json',
      },
      dependencies: ['setup'],
    },

    {
      name: 'Mobile Safari',
      use: {
        ...devices['iPhone 13'],
        storageState: 'tests/.auth/user.json',
      },
      dependencies: ['setup'],
    },
  ],

  /*
   * DO NOT start local dev server - Tilt manages the services
   * The frontend is served through K8s ingress
   */
  // webServer: undefined,
});
