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

const port = Number.parseInt(process.env.PORT ?? "4173", 10);
const defaultBaseUrl = `http://127.0.0.1:${port}`;
const baseURL = process.env.BASE_URL ?? defaultBaseUrl;
const reuseExistingServer = !process.env.CI;
const configuredWorkers = process.env.PLAYWRIGHT_WORKERS
  ? Number.parseInt(process.env.PLAYWRIGHT_WORKERS, 10)
  : undefined;

export default defineConfig({
  testDir: "./tests",
  fullyParallel: false,
  forbidOnly: !!process.env.CI,
  retries: process.env.CI ? 2 : 0,
  workers: configuredWorkers ?? 1,
  reporter: process.env.CI ? [["html", { open: "never" }], ["list"]] : "html",
  use: {
    baseURL,
    trace: "on-first-retry",
    screenshot: "only-on-failure",
    video: "retain-on-failure",
    locale: process.env.LOCALE ?? "ko-KR",
  },
  projects: [
    {
      name: "webkit-desktop",
      use: {
        ...devices["Desktop Safari"],
        serviceWorkers: "block",
      },
    },
    {
      name: "webkit-mobile-webapp",
      use: {
        ...devices["iPhone 13"],
        serviceWorkers: "block",
      },
    },
    {
      name: "chromium-desktop",
      use: {
        ...devices["Desktop Chrome"],
        serviceWorkers: "block",
      },
    },
    {
      name: "firefox-desktop",
      use: {
        ...devices["Desktop Firefox"],
        serviceWorkers: "block",
      },
    },
    {
      name: "chromium-mobile-webapp",
      use: {
        ...devices["Pixel 7"],
        serviceWorkers: "block",
      },
    },
  ],
  webServer: process.env.BASE_URL
    ? undefined
    : {
        command: "node ./scripts/serve-userfront-build.mjs",
        url: defaultBaseUrl,
        reuseExistingServer,
        timeout: 120_000,
      },
});
