// The Lucia project.
// Copyright 2023-2026 DSP, inc.  All rights reserved.
// Authors:
//   chiayin.kuo@dsp.im (chiayin), 2023/1/31
//   cindy.chang@dsp.im (Cindy Chang), 2024/7/9
//   imacat.yang@dsp.im (imacat), 2026/3/6
/**
 * @module vite.config
 *   Vite build configuration with dev server proxy,
 *   path aliases, and test environment settings.
 */

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

/**
 * Builds Vite proxy configuration when backend target is available.
 * @param {Record<string, string>} env - Loaded environment variables.
 * @returns {Record<string, object>|undefined} Proxy config, or undefined when no target is configured.
 */
function createApiProxy(env) {
  if (!env.VUE_APP_API_URL) {
    console.warn(
      "[vite] VUE_APP_API_URL is not set; /api proxy is disabled for this run.",
    );
    return undefined;
  }

  return {
    "/api": {
      target: env.VUE_APP_API_URL,
      changeOrigin: true,
      rewrite: (path) => path.replace(/^\/api/, ""),
    },
  };
}

export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd());
  const proxy = createApiProxy(env);

  return {
    cacheDir: env.VITE_CACHE_DIR || undefined,
    plugins: [vue()],
    base: "/",
    resolve: {
      alias: {
        util: "util/",
        "@": fileURLToPath(new URL("./src", import.meta.url)),
        "/images": "src/assets/images",
      },
    },
    server: {
      host: "localhost",
      port: 58249,
      proxy,
    },
    preview: {
      host: "localhost",
      port: 4173,
      proxy,
    },
    optimizeDeps: {
      include: ["vue", "vue-router", "pinia", "axios"],
    },
    build: {
      commonjsOptions: {
        transformMixedEsModules: true, // Enable @walletconnect/web3-provider which has some code in CommonJS
      },
      rollupOptions: {
        output: {
          manualChunks: {
            "vue-core": ["vue", "vue-router", "pinia"],
            "primevue": ["primevue", "@primevue/themes"],
            "cytoscape": [
              "cytoscape",
              "cytoscape-dagre",
              "cytoscape-fcose",
              "cytoscape-cola",
              "cytoscape-popper",
            ],
            "charts": ["chart.js", "vue-chartjs", "chartjs-adapter-moment", "chartjs-plugin-datalabels"],
            "vendor": ["sweetalert2", "lodash-es", "axios", "moment", "decimal.js"],
          },
        },
      },
    },
    test: {
      globals: true,
      environment: "jsdom",
      environmentOptions: {
        jsdom: { url: "http://localhost:3000" },
      },
      setupFiles: ["./tests/setup-msw.js"],
      exclude: ["tests/e2e/**", "node_modules/**"],
      // reporter: ['text', 'json', 'html', 'vue'],
    },
  };
});
