import path from "node:path";
import { fileURLToPath } from "node:url";

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

const backendBaseUrl = "http://127.0.0.1:5150";
const frontendBaseUrl = "http://127.0.0.1:4321";
const isCi = Boolean(process.env.CI);
const webPushChannel =
  process.env.PLAYWRIGHT_WEB_PUSH_CHANNEL ??
  (process.platform === "win32" ? "msedge" : undefined);
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const repoRoot = path.resolve(__dirname, "..");

export default defineConfig({
  testDir: "./tests",
  testMatch: /web-push\.real\.spec\.ts/,
  fullyParallel: false,
  workers: 1,
  timeout: 180_000,
  expect: {
    timeout: 20_000,
  },
  reporter: [["list"]],
  use: {
    ...devices["Desktop Chrome"],
    channel: webPushChannel,
    baseURL: frontendBaseUrl,
    headless: true,
    trace: "on-first-retry",
    screenshot: "only-on-failure",
    video: "retain-on-failure",
  },
  webServer: [
    {
      command: "cargo loco start --server-and-worker",
      cwd: path.resolve(repoRoot, "backend"),
      url: `${backendBaseUrl}/api/site_settings`,
      reuseExistingServer: false,
      stdout: "pipe",
      stderr: "pipe",
      env: {
        ...process.env,
        DATABASE_URL:
          process.env.DATABASE_URL ??
          "postgres://postgres:postgres%402025%21@10.0.0.2:5432/termi-api_development",
        REDIS_URL: process.env.REDIS_URL ?? "redis://127.0.0.1:6379",
        TERMI_ADMIN_LOCAL_LOGIN_ENABLED:
          process.env.TERMI_ADMIN_LOCAL_LOGIN_ENABLED ?? "true",
      },
    },
    {
      command: "pnpm dev --host 127.0.0.1 --port 4321",
      cwd: path.resolve(repoRoot, "frontend"),
      url: frontendBaseUrl,
      reuseExistingServer: false,
      stdout: "pipe",
      stderr: "pipe",
      env: {
        ...process.env,
        PUBLIC_API_BASE_URL: `${backendBaseUrl}/api`,
        INTERNAL_API_BASE_URL: `${backendBaseUrl}/api`,
        PUBLIC_IMAGE_ALLOWED_HOSTS: "127.0.0.1,127.0.0.1:5150",
      },
    },
  ],
});
