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

// https://vitejs.dev/config/
export default defineConfig(({ command, mode }) => {
  // 加载环境变量
  const env = loadEnv(mode, process.cwd(), '')
  
  // 根据模式设置不同的配置
  const isDevLocal = mode === 'dev-local'
  const isDev = mode === 'dev'
  const isTest = mode === 'test'
  const isProd = mode === 'prod'
  
  return {
    plugins: [vue()],
    resolve: {
      alias: {
        '@': resolve(__dirname, 'src'),
      },
    },
    server: {
      port: isDevLocal || isDev ? 3100 : isTest ? 3101 : 3102,
      host: true,
      open: true, // 自动打开浏览器
      proxy: {
        '/api': {
          target: env.VITE_API_BASE_URL || 'http://localhost:8100',
          changeOrigin: true,
        },
        '/oauth': {
          target: env.VITE_API_BASE_URL || 'http://localhost:8100',
          changeOrigin: true,
        },
      },
    },
    build: {
      outDir: `dist-${mode}`, // 不同环境输出到不同目录
      sourcemap: isDevLocal || isDev || isTest, // 开发和测试环境生成 sourcemap
      minify: isProd ? 'terser' : false, // 生产环境压缩
      rollupOptions: {
        output: {
          // 根据环境设置不同的文件名
          entryFileNames: `assets/[name]-${mode}.[hash].js`,
          chunkFileNames: `assets/[name]-${mode}.[hash].js`,
          assetFileNames: `assets/[name]-${mode}.[hash].[ext]`,
          manualChunks: {
            vue: ['vue', 'vue-router', 'pinia'],
            element: ['element-plus', '@element-plus/icons-vue'],
            utils: ['axios', 'js-cookie', 'dayjs'],
          },
        },
      },
      // 生产环境优化
      ...(isProd && {
        terserOptions: {
          compress: {
            drop_console: true, // 移除 console
            drop_debugger: true, // 移除 debugger
          },
        },
      }),
    },
    define: {
      // 注入环境变量到代码中
      __APP_ENV__: JSON.stringify(mode),
      __BUILD_TIME__: JSON.stringify(new Date().toISOString()),
    },
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: `@import "@/styles/variables.scss";`,
        },
      },
    },
  }
})