import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import path from "path";
import { loadEnv } from "vite";
import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import { ElementPlusResolver } from "unplugin-vue-components/resolvers";

export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd());
  const { VITE_APP_ENV, VITE_APP_BASE_API, VITE_APP_URL } = env;

  let buildConfig = {};

  if (mode === "test") {
    buildConfig = {
      outDir: "dist",
      // 测试环境的其他特定构建配置
    };
  } else if (mode === "prod") {
    buildConfig = {
      outDir: "dist",
      minify: "terser",
      // 生产环境的其他特定构建配置
    };
  }

  return {
    base: VITE_APP_ENV === "production" ? "/" : "/",
    plugins: [
      vue(),
      AutoImport({
        resolvers: [ElementPlusResolver()],
      }),
      Components({
        resolvers: [ElementPlusResolver()],
      }),
    ],
    css: {
      preprocessorOptions: {
        less: {
          javascriptEnabled: true,
        },
      },
    },
    resolve: {
      alias: {
        "@": path.resolve(__dirname, "./src"),
      },
      extensions: [".mjs", ".js", ".ts", ".jsx", ".tsx", ".json", ".vue"],
    },
    server: {
      port: 80,
      host: true,
      hmr: true,
      open: true,
      proxy: {
        [VITE_APP_BASE_API]: {
          target: VITE_APP_URL,
          changeOrigin: true,
          rewrite: (p) => p.replace(/^\/dev-api/, ""),
        },
      },
    },
    build: buildConfig,
  };
});
