import path from "path"
import { fileURLToPath } from "url"
import { defineConfig } from "vitest/config"
import { playwright } from "@vitest/browser-playwright"
import tsconfigPaths from "vite-tsconfig-paths"

const __dirname = path.dirname(fileURLToPath(import.meta.url))
const srcDir = path.resolve(__dirname, "./src")
const convexDir = path.resolve(__dirname, "./convex")
const isCI = process.env.CI === "true"
const isBrowserRun = process.env.VITEST_BROWSER === "true"

process.env.DATABASE_URL =
  process.env.DATABASE_URL ?? "postgresql://postgres:postgres@localhost:5432/sistema_test?schema=public"

export default defineConfig({
  root: __dirname,
  plugins: [tsconfigPaths()],
  resolve: {
    alias: {
      "@": srcDir,
      "@/convex": convexDir,
    },
  },
  test: {
    globals: true,
    setupFiles: isBrowserRun ? ["./tests/setup.browser.ts"] : ["./vitest.setup.node.ts"],
    pool: (process.env.VITEST_POOL as "threads" | "forks" | "vmThreads" | undefined) ?? "threads",
    testTimeout: isBrowserRun ? 30000 : 15000,
    coverage: {
      provider: "v8",
      include: ["src/**/*.{ts,tsx}", "convex/**/*.ts"],
      exclude: ["**/*.d.ts", "**/*.test.*", "tests/**"],
      reportsDirectory: "./coverage",
    },
    deps: {
      registerNodeLoader: true,
    },
    alias: {
      "@": srcDir,
      "@/convex": convexDir,
    },
    browser: {
      enabled: isBrowserRun,
      provider: playwright({
        launchOptions: {
          headless: isCI ? true : undefined,
        },
      }),
      instances: [
        {
          browser: "chromium",
          launch: {
            headless: isCI ? true : false,
          },
        },
      ],
      trace: isCI ? "on-first-retry" : "off",
    },
    environment: "jsdom",
    include: ["src/**/*.test.ts", "tests/**/*.test.ts"],
    exclude: isBrowserRun ? [] : ["tests/browser/**/*.browser.test.ts"],
  },
})
