import { defineConfig, mergeConfig, type UserConfig } from 'vite'
import { resolve } from 'path'
import babel from '@rollup/plugin-babel'
import dts from 'vite-plugin-dts'

export default defineConfig(env => {
  const config: UserConfig = {
    // 插件配置
    plugins: [
      // 集成Babel处理兼容性，完全使用外部babel配置文件
      babel({
        babelHelpers: 'bundled',
        extensions: ['.js', '.jsx', '.ts', '.tsx'],
        // 指定使用根目录的babel配置文件
        configFile: resolve(__dirname, '../../babel.config.js'),
        // 确保只处理源代码，不处理node_modules
        exclude: 'node_modules/**',
      }),
      dts({
        entryRoot: 'src',
        // 输出目录
        outDir: 'dist/@types',
        // 包含的文件
        include: ['src/**/*'],
        // 排除的文件
        exclude: ['src/**/*.test.ts', 'src/**/*.spec.ts', 'templates/**/*'],
        // 生成类型声明文件
        insertTypesEntry: true,
        // 复制非TypeScript文件
        copyDtsFiles: true,
        // 静态导入
        staticImport: true,
        // 清理输出目录
        cleanVueFileName: true,
      }),
    ],

    resolve: {
      // alias需要在根配置中映射
    },

    optimizeDeps: {
      // 默认已排除 node_modules，如需额外排除可添加
      exclude: [],
      esbuildOptions: {
        // 禁用 esbuild 的 TypeScript 转译，让 Babel 处理
        tsconfigRaw: {} as any,
      },
    },

    // 构建配置
    build: {
      lib: {
        entry: {
          index: resolve(__dirname, 'src/index.ts'),
        },
        name: 'MyLib', // UMD模式下的全局变量名（如window.MyUtils）
        formats: ['es', 'cjs'],
        fileName: (format: any, fileName: string) => `${format}/${fileName}.js`,
      },
      rollupOptions: {
        // 排除外部依赖（不打包进库，由使用者自行安装）
        external: (id: string) => {
          // 将 peerDependencies 设为外部依赖
          if (id === 'vue' || id.startsWith('vue/')) return true
          if (id === 'lodash-es' || id.startsWith('lodash-es/')) return true

          // 将 Node.js 内置模块设为外部依赖
          const nodeBuiltins = [
            'fs',
            'path',
            'url',
            'util',
            'crypto',
            'stream',
            'events',
            'buffer',
            'querystring',
            'os',
            'child_process',
            'cluster',
          ]
          if (nodeBuiltins.includes(id)) return true

          return false
        },
        output: {
          // 为外部依赖指定全局变量名（仅UMD模式需要）
          globals: {
            vue: 'Vue',
            'lodash-es': '_', // 当使用UMD时，window._ 对应 lodash-es
          },
        },
      },
    },
  }
  return config
})
