import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import { resolve } from "path";
import envConfig from "./env.config.js";
import scssVariables from "./src/styles/variables.scss.js";

const scssAdditionalData = [
  '@use "sass:color" as color;',
  ...Object.keys(scssVariables).map(
    (k) => `$${k.replace("_", "-")}: ${scssVariables[k]};`
  ),
].join("\n");

export default defineConfig(({ mode }) => {
  const currentEnv = envConfig[mode] || envConfig.development;

  return {
    plugins: [vue()],
    resolve: {
      alias: {
        "@": resolve(__dirname, "src"),
      },
      extensions: [".mjs", ".js", ".ts", ".jsx", ".tsx", ".json", ".vue"],
    },
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: scssAdditionalData,
          silenceDeprecations: ["legacy-js-api"],
        },
      },
    },
    server: {
      host: "127.0.0.1",
      port: 8082,
      open: false,
      proxy: {
        "/ws": {
          target: "https://apis.map.qq.com",
          changeOrigin: true,
          ws: false,
        },
        "/v3/elevation": {
          target: "https://restapi.amap.com",
          changeOrigin: true,
          ws: false,
        },
      },
    },
    build: {
      target: "es2020",
      outDir: "dist",
      assetsDir: "assets",
      sourcemap: false,
      minify: "esbuild",
      rollupOptions: {
        output: {
          chunkFileNames: "js/[name]-[hash].js",
          entryFileNames: "js/[name]-[hash].js",
          assetFileNames: "[ext]/[name]-[hash].[ext]",
          manualChunks: {
            vue: ["vue", "vue-router"],
            elementPlus: ["element-plus"],
            ol: ["ol"],
          },
        },
      },
    },
    define: {
      VE_ENV: {
        MODE: JSON.stringify(currentEnv.NODE_ENV),
        SERVER: JSON.stringify(currentEnv.SERVER),
        PYSERVER: JSON.stringify(currentEnv.PYSERVER),
        NEW_SERVER: JSON.stringify(currentEnv.NEW_SERVER),
      },
      __VUE_PROD_HYDRATION_MISMATCH_DETAILS__: "false",
    },
    optimizeDeps: {
      include: ["vue", "vue-router", "element-plus", "axios", "dayjs", "ol"],
    },
  };
});
