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

// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
  // 加载环境变量
  const env = loadEnv(mode, process.cwd(), '')
  
  // 自定义重定向插件
  const redirectPlugin = () => {
    return {
      name: 'redirect-plugin',
      configureServer(server) {
        server.middlewares.use('/login', (req, res, next) => {
          res.writeHead(302, { Location: '/farm/login' })
          res.end()
        })
      }
    }
  }
  
  return {
    base: '/farm/',
    plugins: [vue(), redirectPlugin()],
    resolve: {
      alias: {
        '@': resolve(__dirname, 'src')
      }
    },
    server: {
      port: 5300,
      host: '0.0.0.0',
      proxy: {
        '/api': {
          target: env.VITE_API_FULL_URL?.replace('/api', '') || 'http://localhost:5350',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, '/api')
        }
      },
      // 开发环境重定向配置
      middlewareMode: false,
      fs: {
        strict: false
      }
    },
    build: {
      outDir: 'dist',
      assetsDir: 'assets',
      rollupOptions: {
        output: {
          assetFileNames: 'assets/[name]-[hash][extname]',
          chunkFileNames: 'assets/[name]-[hash].js',
          entryFileNames: 'assets/[name]-[hash].js'
        }
      }
    },
    define: {
      // 将环境变量注入到应用中
      __APP_ENV__: JSON.stringify(env),
      // 在生产环境中强制使用正确的API URL
      'import.meta.env.VITE_API_BASE_URL': JSON.stringify(
        mode === 'production' ? 'https://ad.liaoniuyun.com/farm/api' : (env.VITE_API_BASE_URL || '/api')
      )
    }
  }
})