import path from 'node:path';

import vue from '@vitejs/plugin-vue';
import vueJsx from '@vitejs/plugin-vue-jsx';
import { AntDesignVueResolver } from 'unplugin-vue-components/resolvers';
import Components from 'unplugin-vue-components/vite';
import { defineConfig, loadEnv } from 'vite';
import mkcert from 'vite-plugin-mkcert';
import qiankun from 'vite-plugin-qiankun';

export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd());
  const isDev = env.VITE_NODE_ENV === 'development';

  return {
    plugins: [
      vue(),
      vueJsx(),
      isDev && mkcert(),
      qiankun('y-code-app', {
        useDevMode: isDev,
      }),
      Components({
        resolvers: [
          AntDesignVueResolver({
            importStyle: 'less',
          }),
        ],
      }),
    ],

    server: isDev
      ? {
          cors: true,
          port: Number(env.VITE_PORT),
        }
      : undefined,

    resolve: {
      alias: {
        '@': path.resolve(__dirname, './src'),
      },
    },

    css: {
      preprocessorOptions: {
        less: {
          javascriptEnabled: true, // 启用 Less 的 JavaScript 功能，通常用于 Ant Design
        },
      },
    },

    // 启用顶级 await 支持
    esbuild: {
      target: 'esnext',
      supported: {
        'top-level-await': true,
      },
    },

    // 确保构建输出支持顶级 await
    build: {
      target: 'esnext',
      // outDir: path.resolve(process.cwd(), "../../dist/y-code-v1"),
      // emptyOutDir: true,
    },
  };
});
