import { reactRouter } from "@react-router/dev/vite";
import tailwindcss from "@tailwindcss/vite";
import { defineConfig, type Plugin } from "vite";

/**
 * Browser/IDE probes (e.g. /json/version) hit the RR handler and log noisy
 * "No route matches URL" errors. Short-circuit them before the router.
 */
function ignoreDevProbeRequests(): Plugin {
  const ignoredExact = new Set([
    "/json/version",
    "/.well-known/appspecific/com.chrome.devtools.json",
  ]);

  return {
    name: "ignore-dev-probe-requests",
    configureServer(server) {
      server.middlewares.use((req, res, next) => {
        const pathname = req.url?.split("?")[0] ?? "";
        if (!ignoredExact.has(pathname)) {
          next();
          return;
        }

        res.statusCode = 204;
        res.end();
      });
    },
  };
}

const apiProxyTarget = process.env.B2BFLOW_API_PROXY || "http://127.0.0.1:3000";

/**
 * Split stable vendor libs from app/route chunks.
 * Route modules are already code-split by the React Router Vite plugin.
 */
function vendorManualChunk(id: string): string | undefined {
  if (!id.includes("node_modules")) {
    return undefined;
  }

  // Match package roots so "react-router" is not lumped into "react".
  if (
    /[/\\]node_modules[/\\](react-dom|react|scheduler)[/\\]/.test(id)
  ) {
    return "vendor-react";
  }

  if (
    /[/\\]node_modules[/\\](react-router|@react-router)[/\\]/.test(id)
  ) {
    return "vendor-router";
  }

  return "vendor";
}

export default defineConfig({
  plugins: [ignoreDevProbeRequests(), tailwindcss(), reactRouter()],
  resolve: {
    tsconfigPaths: true,
  },
  build: {
    target: "es2022",
    cssCodeSplit: true,
    sourcemap: false,
    assetsInlineLimit: 4096,
    modulePreload: {
      polyfill: true,
    },
    reportCompressedSize: true,
    chunkSizeWarningLimit: 600,
    rollupOptions: {
      output: {
        manualChunks: vendorManualChunk,
      },
    },
  },
  server: {
    // Forward authenticated Express routes during local embedded-app development.
    proxy: {
      "/api": {
        target: apiProxyTarget,
        changeOrigin: true,
        // Keep React Router /api/customers on the Vite app — only proxy Express APIs.
        bypass(req) {
          const path = req.url?.split("?")[0] ?? "";
          if (path === "/api/customers" || path.startsWith("/api/customers/")) {
            return req.url;
          }
        },
      },
      "/auth": { target: apiProxyTarget, changeOrigin: true },
      "/webhooks": { target: apiProxyTarget, changeOrigin: true },
      "/health": { target: apiProxyTarget, changeOrigin: true },
    },
  },
});
