import { defineConfig, loadEnv, type PluginOption } from "vite";
import react from "@vitejs/plugin-react";
import path from "path";
import { pathToFileURL } from "url";
// import { visualizer } from "rollup-plugin-visualizer";

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

  return {
    plugins: [
      // visualizer({ open: true }), 
      react(), expressPlugin(),],
    resolve: {
      alias: {
        "@": path.resolve(__dirname, "src"),
      },
    },
    build: {
      rollupOptions: {
        output: {
          manualChunks(id) {
            if (id.includes('node_modules')) {
              return id.toString().split('node_modules/')[1].split('/')[0];
            }
          },
        },
      },
      outDir: "dist/client",
    },
    server: {
      host: true,
      allowedHosts: ["drier-envision-cradle.ngrok-free.dev"]

    },
    define: {
      "process.env.GEMINI_API_KEY": JSON.stringify(env.GEMINI_API_KEY),
    },
  };
});

function expressPlugin(): PluginOption {
  return {
    name: " vite:express",
    apply: "serve",

    async configureServer(viteServer) {
      const serverPath = pathToFileURL(
        path.resolve(__dirname, "./server/index.ts")
      ).href;

      const { createServer } = await import(serverPath);
      const app = await createServer();

      viteServer.middlewares.use(app);

      console.log("✅ Express API mounted at /api");
    },
  };
}
