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

const baseURL = process.env.PLAYWRIGHT_BASE_URL ?? "http://127.0.0.1:3000";
const isRealBackendRun = process.env.E2E_REAL_BACKEND === "1";
const shouldStartLocalServer =
  !isRealBackendRun && baseURL.startsWith("http://127.0.0.1");
const browserChannel =
  process.env.PLAYWRIGHT_USE_SYSTEM_CHROME === "1" ? "chrome" : undefined;

export default defineConfig({
  testDir: "./e2e/specs",
  fullyParallel: true,
  forbidOnly: Boolean(process.env.CI),
  retries: process.env.CI ? 2 : 0,
  workers: process.env.CI ? 1 : undefined,
  reporter: process.env.CI
    ? [["list"], ["html", { open: "never" }]]
    : [["list"], ["html", { open: "never" }]],
  use: {
    baseURL,
    trace: "on-first-retry",
    screenshot: "only-on-failure",
    video: "retain-on-failure",
  },
  webServer: shouldStartLocalServer
    ? {
        command: "pnpm dev -H 127.0.0.1 -p 3000",
        url: baseURL,
        reuseExistingServer: !process.env.CI,
        timeout: 120_000,
      }
    : undefined,
  projects: [
    {
      name: "mock-chromium",
      testMatch: /mock\/.*\.spec\.ts/,
      use: {
        ...devices["Desktop Chrome"],
        channel: browserChannel,
      },
    },
    {
      name: "mock-mobile-chrome",
      testMatch: /mock\/.*\.spec\.ts/,
      use: {
        ...devices["Pixel 7"],
        channel: browserChannel,
      },
    },
    {
      name: "real-backend",
      testMatch: /real\/.*\.spec\.ts/,
      use: {
        ...devices["Pixel 7"],
        channel: browserChannel,
      },
    },
    {
      name: "prod-smoke",
      testMatch: /real\/.*\.spec\.ts/,
      use: {
        ...devices["Pixel 7"],
        channel: browserChannel,
      },
    },
  ],
});
