import path from "path";
import { fileURLToPath } from "url";
import tailwindcss from "@tailwindcss/vite";
import react from "@vitejs/plugin-react";
import { defineConfig } from "vite";
import { viteSingleFile } from "vite-plugin-singlefile";

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// https://vite.dev/config/
export default defineConfig({
  plugins: [
    react(),
    tailwindcss(),
    viteSingleFile(),
    {
      name: "long-timeouts",
      configureServer(server) {
        // Large graph snapshots can take minutes; keep the dev server from killing the request.
        const httpServer = server.httpServer;
        if (!httpServer) return;
        const ms30m = 30 * 60 * 1000;
        httpServer.headersTimeout = ms30m;
        httpServer.requestTimeout = ms30m;
        httpServer.keepAliveTimeout = ms30m;
      },
    },
  ],
  resolve: {
    alias: {
      "@": path.resolve(__dirname, "src"),
    },
  },
  server: {
    proxy: {
      // Backend is reachable as http://backend:8000 inside docker-compose; localhost outside.
      "/api": {
        target: process.env.VITE_BACKEND_URL || "http://localhost:8000",
        changeOrigin: true,
        configure: (proxy) => {
          proxy.on("error", (err) => {
            // Surface upstream timeouts/socket errors in `docker compose logs frontend`.
            console.error("[vite-proxy] /api error:", err);
          });
        },
        // The initial graph snapshot can take minutes with large limits (SPARQL + layout + labels).
        // Prevent the dev proxy from timing out and returning a 500 to the browser.
        timeout: 30 * 60 * 1000,
        proxyTimeout: 30 * 60 * 1000,
      },
    },
  },
});
