import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import { federation } from '@module-federation/vite'
import { resolve, dirname } from 'path'
import { fileURLToPath } from 'url'
import fs from 'fs'

const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)

// 开发环境 shared 模块地址
const DEV_SHARED_URL = 'https://localhost:7000/shared/remoteEntry.js'
// 生产环境使用相对路径，通过 Nginx 代理访问
const PROD_SHARED_URL = '/shared/remoteEntry.js'

export default defineConfig(({ mode }) => {
  const isDev = mode === 'development'
  const sharedEntry = isDev ? DEV_SHARED_URL : PROD_SHARED_URL

  return {
    base: '/bidding/',
    
    plugins: [
      vue({
        script: {
          defineModel: true,
          propsDestructure: true
        }
      }),
      vueJsx(),
      federation({
        name: 'bidding',
        remotes: {
          shared: {
            type: 'module',
            name: 'shared',
            entry: sharedEntry
          }
        },
        shared: {
          vue: {},
          'vue-router': {},
          'element-plus': {},
          axios: {}
        }
      })
    ],
    
    define: {
      __VUE_OPTIONS_API__: true,
      __VUE_PROD_DEVTOOLS__: true,
      __VUE_PROD_HYDRATION_MISMATCH_DETAILS__: true
    },
    
    resolve: {
      alias: {
        '@': resolve(__dirname, 'src')
      }
    },
    
    server: {
      port: 7002,
      host: true,
      cors: true,
      open: '/bidding/',
      https: (() => {
        try {
          return {
            key: fs.readFileSync('C:/Users/FK05/443/localhost+3-key.pem'),
            cert: fs.readFileSync('C:/Users/FK05/443/localhost+3.pem')
          }
        } catch {
          return undefined
        }
      })(),
      hmr: {
        path: '/@vite/client',
        port: 7002
      },
      proxy: {
        '/api': {
          target: 'http://localhost:8180',
          changeOrigin: true,
          rewrite: (path: string) => path.replace(/^\/api/, '')
        }
      }
    },
    
    build: {
      target: 'esnext',
      outDir: 'dist',
      sourcemap: true
      // 注意：不要使用 manualChunks 分割 vue/vue-router/element-plus
      // 因为它们已经在 Module Federation 的 shared 中声明
      // 同时使用会导致循环依赖死锁
    },
    
    preview: {
      port: 7002,
      host: true,
      cors: true,
      https: (() => {
        try {
          return {
            key: fs.readFileSync('C:/Users/FK05/443/localhost+3-key.pem'),
            cert: fs.readFileSync('C:/Users/FK05/443/localhost+3.pem')
          }
        } catch {
          return undefined
        }
      })(),
      headers: {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
        'Access-Control-Allow-Headers': 'Content-Type, Authorization'
      }
    }
  }
})
