import path from "path";
import { defineConfig, loadEnv } from "vite";
import createVitePlugins from "./vite/plugins";

// https://vitejs.dev/config/
export default defineConfig(({ mode, command }) => {
  const env = loadEnv(mode, process.cwd());
  const { VITE_APP_ENV, VITE_APP_CAS_ENABLE } = env;

  return {
    // 部署生产环境和开发环境下的URL.
    // 根据 .env 中的 CAS 开关动态设置 base 路径
    // 注意:不要从 src/settings 引入,因为 vite 配置运行在 Node 环境,无法使用 import.meta.env
    base:
      VITE_APP_ENV === "production"
        ? VITE_APP_CAS_ENABLE === "true"
          ? "/cas/"
          : "/srs/"
        : "/",
    plugins: createVitePlugins(env, command === "build"),
    resolve: {
      // https://cn.vitejs.dev/config/#resolve-alias
      alias: {
        "~": path.resolve(__dirname, "./"),
        "@": path.resolve(__dirname, "./src"),
      },
      // https://cn.vitejs.dev/config/#resolve-extensions
      extensions: [".mjs", ".js", ".ts", ".jsx", ".tsx", ".json", ".vue"],
    },
    server: {
      host: true,
      open: true,
      proxy: {
        // https://cn.vitejs.dev/config/#server-proxy
        "/dev-api": {
          target: "http://localhost:8080", // 测试
          // target: 'http://172.16.129.101:8080', // 正式环境
          changeOrigin: true,
          rewrite: (p) => p.replace(/^\/dev-api/, ""),
        },
        // 添加对第三方 API 的代理配置
        "/api/v1/jssdk/upload": {
          target: "https://px.effirst.com",
          changeOrigin: true,
          rewrite: (p) =>
            p.replace(/^\/api\/v1\/jssdk\/upload/, "/api/v1/jssdk/upload"),
        },
      },
    },
    // fix:error:stdin>:7356:1: warning: "@charset" must be the first rule in the file
    css: {
      postcss: {
        plugins: [
          {
            postcssPlugin: "internal:charset-removal",
            AtRule: {
              charset: (atRule) => {
                if (atRule.name === "charset") {
                  atRule.remove();
                }
              },
            },
          },
        ],
      },
    },
    build: {
      target: "es2015", // 指定编译目标
      minify: "terser",
      terserOptions: {
        compress: {
          drop_console: true,
          drop_debugger: true,
        },
      },
    },
  };
});
