import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";

export function redirectSubsystemEntry(req, res, next) {
  const rawUrl = req.url || "";
  const [pathname, query = ""] = rawUrl.split("?");

  if (pathname === "/money" || pathname === "/money/") {
    res.statusCode = 301;
    res.setHeader("Location", `/finance/${query ? `?${query}` : ""}`);
    res.end();
    return;
  }

  if (pathname === "/databi/social") {
    res.statusCode = 301;
    res.setHeader("Location", `/databi/social/${query ? `?${query}` : ""}`);
    res.end();
    return;
  }

  if (pathname === "/databi" || pathname === "/finance" || pathname === "/external-admin") {
    res.statusCode = 301;
    res.setHeader("Location", `${pathname}/${query ? `?${query}` : ""}`);
    res.end();
    return;
  }

  if (pathname === "/ops-center") {
    res.statusCode = 301;
    res.setHeader("Location", `/ops-center/${query ? `?${query}` : ""}`);
    res.end();
    return;
  }

  if (
    pathname.startsWith("/external-admin/") &&
    pathname !== "/external-admin/" &&
    !pathname.startsWith("/external-admin/src/") &&
    !pathname.split("/").at(-1).includes(".")
  ) {
    // Vite's generic SPA fallback points unknown paths at the main admin entry; keep external-admin deep links inside its isolated document.
    req.url = `/external-admin/index.html${query ? `?${query}` : ""}`;
  }

  next();
}

function subsystemEntryPlugin() {
  return {
    name: "hyapp-subsystem-entry",
    configureServer(server) {
      server.middlewares.use(redirectSubsystemEntry);
    },
    configurePreviewServer(server) {
      server.middlewares.use(redirectSubsystemEntry);
    }
  };
}

export default defineConfig({
  build: {
    modulePreload: false,
    rollupOptions: {
      output: {
        manualChunks(id) {
          // Keep the admin shell dependency graph shallow; GAAP resets the browser HTTP/2 connection when the first screen fans out into many module requests.
          if (id.includes("node_modules")) {
            return "vendor";
          }
          if (id.includes("/src/shared/") || id.includes("/src/app/")) {
            return "shared";
          }
        }
      },
      input: {
        admin: new URL("./index.html", import.meta.url).pathname,
        databi: new URL("./databi/index.html", import.meta.url).pathname,
        databiSocial: new URL("./databi/social/index.html", import.meta.url).pathname,
        finance: new URL("./finance/index.html", import.meta.url).pathname,
        externalAdmin: new URL("./external-admin/index.html", import.meta.url).pathname,
        opsCenter: new URL("./ops-center/index.html", import.meta.url).pathname
      }
    }
  },
  css: {
    modules: {
      generateScopedName: "hy-[name]__[local]__[hash:base64:5]",
      localsConvention: "camelCaseOnly"
    }
  },
  resolve: {
    alias: {
      "@": new URL("./src", import.meta.url).pathname
    },
    dedupe: ["react", "react-dom", "@emotion/react", "@emotion/styled"]
  },
  optimizeDeps: {
    include: [
      "@emotion/react",
      "@emotion/styled",
      "@mui/material/MenuItem",
      "@mui/material/Select",
      "@mui/material/TextField",
      "@mui/material/styles",
      "react",
      "react-dom",
      "react-dom/client",
      "react/jsx-dev-runtime",
      "react/jsx-runtime"
    ]
  },
  plugins: [subsystemEntryPlugin(), react()],
  server: {
    port: 7001,
    proxy: {
      "/api": {
        target: "http://localhost:13100",
        changeOrigin: true
      },
      "/__api_test__": {
        target: "https://api-test.global-interaction.com",
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/__api_test__/, "")
      },
      "/__api_local__": {
        target: "http://127.0.0.1:13000",
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/__api_local__/, "")
      }
    }
  },
  preview: {
    port: 7001
  },
  test: {
    environment: "jsdom",
    setupFiles: "./src/test/setup.js"
  }
});
