import { defineConfig, loadEnv } from "vite";
import react from "@vitejs/plugin-react";
import tailwindcss from "@tailwindcss/vite";
import { fileURLToPath, URL } from "node:url";

import { transportFromEnv } from "./src/app/transport";

const root = fileURLToPath(new URL(".", import.meta.url));

// Vite config tuned for Tauri v2 (fixed dev port, no clearing the terminal).
//
// Two build artefacts (ticket #74): the default mode emits the desktop bundle
// (`dist`, Tauri IPC transport), and `--mode web` reads `.env.web` to emit the
// browser bundle served by the embedded server (`dist-web`, HTTP+WS transport).
export default defineConfig(({ mode }) => {
  // Same env file resolution Vite applies to `import.meta.env`, so the
  // `__IDEA_TRANSPORT__` constant below is computed from the exact variable
  // `resolveTransport()` reads, through the exact same predicate (#74, F1).
  const env = loadEnv(mode, root);

  return {
    plugins: [react(), tailwindcss()],
    resolve: {
      alias: {
        "@": fileURLToPath(new URL("./src", import.meta.url)),
      },
    },
    define: {
      __IDEA_TRANSPORT__: JSON.stringify(transportFromEnv(env.VITE_TRANSPORT)),
    },
    clearScreen: false,
    server: {
      port: 5173,
      strictPort: true,
    },
    build: {
      target: "es2021",
      outDir: "dist",
    },
  };
});
