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

// https://vite.dev/config/
export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd(), "");

  const webPort = Number(env.WEB_PORT || process.env.WEB_PORT || 5175);
  const apiPort = Number(env.API_PORT || process.env.API_PORT || 5174);

  // dev: use Vite proxy → upstream
  // prod: set VITE_API_URL to absolute base if needed
  const signalBatchTarget = env.VITE_SIGNAL_BATCH_TARGET || process.env.VITE_SIGNAL_BATCH_TARGET || "https://wing.gc-si.dev";

  return {
    plugins: [tailwindcss(), react()],
    resolve: {
      alias: {
        // deck.gl (via loaders.gl) contains a few Node-only helper modules.
        // In browser builds, they should be tree-shaken, but Vite/Rollup may still warn.
        child_process: fileURLToPath(new URL("./src/shared/shims/child_process.ts", import.meta.url)),
      },
    },
    server: {
      // IMPORTANT: keep the web dev server port fixed so it doesn't collide with the API server port.
      // If the port is already taken, fail fast instead of auto-falling-back to the API port (proxy loop -> 500).
      port: webPort,
      strictPort: true,
      proxy: {
        // Optional local API server (future DB-backed APIs etc).
        "/api": {
          target: `http://127.0.0.1:${apiPort}`,
          changeOrigin: true,
        },
        // signal-batch API (선박 위치/항적)
        "/signal-batch": {
          target: signalBatchTarget,
          changeOrigin: true,
          secure: false,
        },
        // 선박 이미지 정적 파일 (nginx alias /pgdata/shipimg/)
        "/shipimg": {
          target: signalBatchTarget,
          changeOrigin: true,
          secure: false,
        },
      },
    },
  };
});
