import { defineConfig } from "vite";
import react from "@vitejs/plugin-react-swc";
import path from "path";
import { componentTagger } from "lovable-tagger";

// https://vitejs.dev/config/
//
// PUBLIC_HOST is set in the repo-root `.env` for docker-compose.prod.yml; Compose passes:
//   VITE_ALLOWED_HOSTS=${PUBLIC_HOST},localhost
// so Vite accepts the Host header when you open http://${PUBLIC_HOST}:${FE_PORT}.
// Proxy target: locally use localhost:4402; in Docker set VITE_DEV_PROXY_TARGET=http://be0:4402
const allowedHostsRaw = process.env.VITE_ALLOWED_HOSTS;
const apiProxyTarget =
  process.env.VITE_DEV_PROXY_TARGET || process.env.VITE_API_URL || "http://localhost:4402";

const allowedHostsExtra = ["rcc-ump.com", "www.rcc-ump.com"];
const viteAllowedHostsList = (allowedHostsRaw ?? "")
  .split(",")
  .map((h) => h.trim())
  .filter(Boolean);
const viteAllowedHosts =
  viteAllowedHostsList.length > 0
    ? [...new Set([...allowedHostsExtra, ...viteAllowedHostsList])]
    : true;

export default defineConfig(({ mode }) => ({
  server: {
    host: "0.0.0.0",
    // Must match docker-compose.prod.yml (FE_PORT maps host → container :8080) and fe0/Dockerfile EXPOSE.
    port: 8080,
    allowedHosts: viteAllowedHosts,
    proxy: {
      // Proxy API requests to backend
      "/api": {
        target: apiProxyTarget,
        changeOrigin: true,
        secure: false,
      },
      // Submitted PDFs live on be0 (`StaticFiles` + SUBMITTED_INITIATIVES_DIR); same as production API host.
      "/submitted-initiatives": {
        target: apiProxyTarget,
        changeOrigin: true,
        secure: false,
      },
      "/test_ollama": {
        target: apiProxyTarget,
        changeOrigin: true,
        secure: false,
      },
    },
  },
  plugins: [react(), mode === "development" && componentTagger()].filter(Boolean),
  resolve: {
    alias: {
      "@": path.resolve(__dirname, "./src"),
    },
  },
  // CJS deps: pre-bundle so Vite dev + Docker mounts resolve reliably.
  optimizeDeps: {
    include: ["docx-preview", "jszip", "pizzip", "pako", "docxtemplater"],
  },
}));
