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, command }) => {
  // dev 和 preview 都需要访问本地 shared 服务
  // command: 'serve' (dev), 'build', 或通过环境变量判断 preview
  const isDev = mode === 'development'
  // preview 模式通过 nginx 代理访问 shared，使用相对路径
  const sharedEntry = isDev ? DEV_SHARED_URL : PROD_SHARED_URL

  return {
    base: '/workcase/',
    
    plugins: [
      vue({
        script: {
          defineModel: true,
          propsDestructure: true
        }
      }),
      vueJsx(),
      federation({
        name: 'workcase',
        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,
      global: 'globalThis'
    },
    
    resolve: {
      alias: {
        '@': resolve(__dirname, 'src')
      }
    },
    
    server: {
      port: 7003,
      host: true,
      cors: true,
      open: '/workcase/',
      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: 7003
      },
      proxy: {
        '/api': {
          target: 'http://localhost:8180',
          changeOrigin: true,
          ws: true,
          rewrite: (path: string) => path.replace(/^\/api/, '')
        }
      }
    },
    preview: {
        port: 7003,
        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'
        }
    },
    build: {
      target: 'esnext',
      outDir: 'dist',
      sourcemap: true
      // 注意：不要使用 manualChunks 分割 vue/vue-router/element-plus
      // 因为它们已经在 Module Federation 的 shared 中声明
      // 同时使用会导致循环依赖死锁
    }
  }
})
