import { defineConfig, loadEnv } from "vite";
import react from "@vitejs/plugin-react";
import { isPwaEventStreamRequest, pwaAllowedHosts, pwaProxyOrigin } from "./vite-hosts.js";

export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd(), "");

  return {
    plugins: [react()],
    server: {
      host: "127.0.0.1",
      port: 43111,
      strictPort: true,
      allowedHosts: pwaAllowedHosts(env),
      proxy: {
        "/api": {
          target: "http://127.0.0.1:43110",
          changeOrigin: false,
          rewrite: (path) => path.replace(/^\/api/, ""),
          configure(proxy) {
            proxy.on("proxyReq", (proxyRequest, request) => {
              if (request.headers.origin || !isPwaEventStreamRequest(request.method, request.url)) return;
              const origin = pwaProxyOrigin(request, env);
              if (origin) proxyRequest.setHeader("origin", origin);
            });
          }
        }
      }
    }
  };
});
