import { fileURLToPath, URL } from "node:url";

import { defineConfig, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";
import vueJsx from "@vitejs/plugin-vue-jsx";
import vueDevTools from "vite-plugin-vue-devtools";

import AutoImport from "unplugin-auto-import/vite";
import { NaiveUiResolver } from "unplugin-vue-components/resolvers";
import Components from "unplugin-vue-components/vite";
import { visualizer } from "rollup-plugin-visualizer";

// https://vite.dev/config/
export default defineConfig(({ mode }) => {
  const env: Record<string, string> = loadEnv(mode, process.cwd(), "VITE_");
  return {
    define: {
      __APP_ENV: JSON.stringify(env),
    },
    plugins: [
      vue(),
      vueJsx(),
      vueDevTools(),
      visualizer({
        open: false,
        gzipSize: true,
        brotliSize: true,
        filename: "analyzer.html",
      }),
      AutoImport({
        imports: ["vue", "vue-router"],
        dts: "./src/types/auto-imports.d.ts",
      }),
      Components({
        resolvers: [NaiveUiResolver()],
        dts: "./src/types/components.d.ts",
      }),
    ],
    resolve: {
      alias: {
        "@": fileURLToPath(new URL("./src", import.meta.url)),
      },
    },
    server: {
      host: "0.0.0.0",
      port: parseInt(env["VITE_APP_PORT"]),
      open: false,
      proxy: {
        [env["VITE_APP_BASE_API"]]: {
          target: env["VITE_APP_PROXY_URL"],
          changeOrigin: true,
          secure: false,
          rewrite: (path) =>
            path.replace(RegExp(`^${env["VITE_APP_BASE_API"]}`), ""),
        },
      },
    },
    build: {
      target: "modules",
      chunkSizeWarningLimit: 1500,
      minify: "terser",
      terserOptions: {
        compress: {
          //生产环境时移除console
          drop_console: env["VITE_DROP_CONSOLE"] as unknown as boolean,
          drop_debugger: env["VITE_DROP_CONSOLE"] as unknown as boolean,
        },
        format: {
          //删除注释
          comments: false,
        },
      },
      rollupOptions: {
        output: {
          assetFileNames: "assets/[ext]/[name]-[hash].[ext]",
          manualChunks(id) {
            if (id.includes("node_modules")) {
              return id
                .toString()
                .split("node_modules/")[1]
                .split("/")[0]
                .toString();
            }
          },
          chunkFileNames(chunkInfo) {
            const facadeModuleId = chunkInfo.facadeModuleId
              ? chunkInfo.facadeModuleId.split("/")
              : [];
            const fileName =
              facadeModuleId[facadeModuleId.length - 2] || "[name]";
            return `js/${fileName}/[name].[hash].js`;
          },
        },
      },
    },
  };
});
