import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'

export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, new URL('.', import.meta.url).pathname, '')
  const releaseId = env.VITE_RELEASE_ID?.trim()
  if (releaseId && !/^[A-Za-z0-9._-]+$/.test(releaseId)) {
    throw new Error('VITE_RELEASE_ID 只能包含字母、数字、点、下划线和短横线')
  }

  return {
    base: env.VITE_APP_BASE || '/',
    plugins: [
      vue(),
      AutoImport({ resolvers: [ElementPlusResolver()] }),
      Components({ resolvers: [ElementPlusResolver()] }),
    ],
    resolve: {
      alias: { '@': new URL('./src', import.meta.url).pathname },
    },
    build: {
      assetsDir: releaseId ? `releases/${releaseId}/assets` : 'assets',
      chunkSizeWarningLimit: 1000,
      rollupOptions: {
        output: {
          manualChunks(id) {
            if (!id.includes('node_modules')) return undefined
            if (id.includes('element-plus')) return 'element-plus'
            if (id.includes('@element-plus/icons-vue')) return 'element-plus-icons'
            if (id.includes('vue-router')) return 'vue-router'
            if (id.includes('pinia')) return 'pinia'
            if (id.includes('axios')) return 'axios'
            return 'vendor'
          },
        },
      },
    },
    server: {
      port: 5174,
      proxy: {
        '/api': { target: 'http://127.0.0.1:8081', changeOrigin: true },
      },
    },
  }
})
