import { fileURLToPath, URL } from 'node:url'

import { defineConfig } 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 Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'

// https://vite.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    vueJsx(),
    vueDevTools(),
    AutoImport({
      resolvers: [ElementPlusResolver()],
      imports: [
        'vue',
        'vue-router',
        'pinia',
      ],
      dts: true
    }),
    Components({
      resolvers: [ElementPlusResolver()],
    }),
  ],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url)),
    },
  },
  build: {
    // 输出目录
    outDir: 'dist',

    // 静态资源目录
    assetsDir: 'assets',

    // 是否生成 source map
    sourcemap: false,

    // CommonJS 配置
    commonjsOptions: {
      transformMixedEsModules: true
    },

    // 构建优化配置
    rollupOptions: {
      output: {
        // 代码分割配置
        chunkFileNames: 'js/[name]-[hash].js',
        entryFileNames: 'js/[name]-[hash].js',
        assetFileNames: (assetInfo) => {
          // 安全地处理 assetInfo
          if (!assetInfo.name) {
            return 'assets/[name]-[hash][extname]'
          }

          const extType = assetInfo.name.split('.').pop()?.toLowerCase() || ''
          if (extType) {
            if (/png|jpe?g|svg|gif|tiff|bmp|ico/i.test(extType)) {
              return `img/[name]-[hash][extname]`
            }
            if (/css/i.test(extType)) {
              return `css/[name]-[hash][extname]`
            }
            if (/woff|woff2|eot|ttf|otf/i.test(extType)) {
              return `fonts/[name]-[hash][extname]`
            }
          }
          return `assets/[name]-[hash][extname]`
        }
      }
    },

    // 构建大小警告阈值（KB）
    chunkSizeWarningLimit: 1000
  },
  server: {
    host: '0.0.0.0',
    port: 8080,
    open: true,
    cors: true,
  },
  base: './'
})
