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

import { defineConfig, loadEnv, UserConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

// https://vite.dev/config/
export default defineConfig(({ mode }): UserConfig => {
  const root = process.cwd()
  const env = loadEnv(mode, root)
  // const isProduction = mode === 'production'

  return {
    base: '/h5/',
    plugins: [vue()].filter(Boolean),
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
      },
    },

    server: {
      open: false,
      proxy: {
        '/api': {
          target: env.VITE_APP_URL,
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, ''),
        },
      },
    },

    build: {
      rollupOptions: {
        output: {
          entryFileNames: `assets/[name].[hash].js`,
          chunkFileNames: `assets/[name].[hash].js`,
          assetFileNames: `assets/[name].[hash].[ext]`,
          // 使用 Vite 原生 manualChunks 替代 chunk-split 插件
          manualChunks(id: string) {
            if (id.includes('node_modules')) {
              if (id.includes('lodash-es')) return 'vendor-lodash'
              if (id.includes('echarts')) return 'vendor-echarts'
              return 'vendor'
            }
          },
        },
      },
    },
  }
})
