import { addCucumberPreprocessorPlugin } from "@badeball/cypress-cucumber-preprocessor";
import { createEsbuildPlugin } from "@badeball/cypress-cucumber-preprocessor/esbuild";
import createBundler from "@bahmutov/cypress-esbuild-preprocessor";
import { devServer } from "@cypress/vite-dev-server";
import { defineConfig } from "cypress";
import viteConfig from "./vite.config";

// Disable GPU for headless/sandboxed environments (e.g. CI containers) where
// no GPU device is available — needed by both e2e and component testing,
// each of which has its own independent `setupNodeEvents`.
function disableGpu(on: Cypress.PluginEvents) {
  on("before:browser:launch", (browser, launchOptions) => {
    if (browser.family === "chromium") {
      launchOptions.args.push("--disable-gpu", "--no-sandbox");
    }
    return launchOptions;
  });
}

export default defineConfig({
  e2e: {
    baseUrl: "http://localhost:5173",
    // User journeys, Gherkin-driven (see docs/testing.md once written) live
    // alongside plain layout-focused `.cy.ts` specs here — both matched by
    // this pattern. Generic component tests are separate, see `component`
    // below.
    specPattern: ["cypress/e2e/**/*.cy.ts", "cypress/e2e/**/*.feature"],
    async setupNodeEvents(on, config) {
      disableGpu(on);

      await addCucumberPreprocessorPlugin(on, config);
      on(
        "file:preprocessor",
        createBundler({
          plugins: [createEsbuildPlugin(config)],
        }),
      );

      return config;
    },
  },

  // Mounts one generic UI component at a time (components/ui/*), no
  // router/backend involved — separate from the e2e suite above, which
  // always exercises a full routed page. Reuses the app's own vite.config.ts
  // (same React plugin, same Sass setup) rather than duplicating it.
  component: {
    specPattern: "cypress/component/**/*.cy.tsx",
    devServer(devServerConfig) {
      return devServer({ ...devServerConfig, viteConfig });
    },
    setupNodeEvents(on) {
      disableGpu(on);
    },
  },
});
