import { defineConfig, devices, chromium } from "@playwright/test";
import os from "node:os";
import path from "node:path";

const apiUrl = "http://localhost:5302";
const appUrl = "http://localhost:3300";
const dataRoot = path.join(os.tmpdir(), `jobtracker-e2e-${process.pid}-${Date.now().toString(36)}`);
const reuseServers = process.env.PLAYWRIGHT_REUSE_SERVERS === "true";
const useStaticExport = process.env.PLAYWRIGHT_STATIC_EXPORT === "true";
const quote = (value: string) => `"${value.replaceAll('"', '\\"')}"`;
const nodeCommand = quote(process.execPath);
const dotnetCommand = quote(process.env.DOTNET_HOST_PATH || "dotnet");
const nextCommand = quote(path.resolve("node_modules/next/dist/bin/next"));
const exportServerCommand = quote(path.resolve("scripts/serve-export.mjs"));

export default defineConfig({
  testDir: "./e2e",
  fullyParallel: false,
  workers: 1,
  retries: process.env.CI ? 1 : 0,
  reporter: process.env.CI ? "github" : "list",
  use: {
    baseURL: appUrl,
    trace: "retain-on-failure",
    screenshot: "only-on-failure",
  },
  projects: [{ name: "chromium", use: { ...devices["Desktop Chrome"] } }],
  webServer: [
    {
      command: `${dotnetCommand} run --no-build --configuration Release --project ../JobTrackerApi/JobTrackerApi.csproj --urls http://localhost:5302`,
      url: `${apiUrl}/health`,
      timeout: 120_000,
      reuseExistingServer: reuseServers,
      env: {
        ASPNETCORE_ENVIRONMENT: "Development",
        Auth__Require: "true",
        Auth__JwtKey: "e2e-only-key-at-least-thirty-two-characters-long",
        Auth__AdminEmail: "e2e@example.test",
        Auth__AdminPassword: "E2ePassword123!",
        Auth__AllowRegistration: "false",
        App__Version: "e2e-verification",
        App__CommitSha: "e2e1234",
        Cors__Origins__0: appUrl,
        Data__Root: dataRoot,
        HttpsRedirection__Enabled: "false",
        CV_PDF_BROWSER_PATH: chromium.executablePath(),
      },
    },
    {
      command: useStaticExport
        ? `${nodeCommand} ${nextCommand} build && ${nodeCommand} ${exportServerCommand}`
        : `${nodeCommand} ${nextCommand} dev --webpack --hostname localhost --port 3300`,
      url: appUrl,
      timeout: 120_000,
      reuseExistingServer: reuseServers,
      env: { NEXT_PUBLIC_API_BASE_URL: `${apiUrl}/api` },
    },
  ],
});
