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)

export default defineConfig(({ mode }) => ({
  // 开发和生产环境都通过nginx代理访问/workcase
  base: '/workcase/',
  
  plugins: [
    vue({
      script: {
        defineModel: true,
        propsDestructure: true
      }
    }),
    vueJsx(),
    federation({
      name: 'workcase',
      remotes: {
        shared: {
          type: 'module',
          name: 'shared',
          entry: 'https://org.xyzh.yslg/shared/remoteEntry.js'
        }
      },
      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/',  // 开发时自动打开到 /workcase/ 路径
    // HTTPS 配置（使用 mkcert 生成的本地开发证书）
    https: {
      key: fs.readFileSync('C:/Users/FK05/443/localhost+3-key.pem'),
      cert: fs.readFileSync('C:/Users/FK05/443/localhost+3.pem')
    },
    hmr: {
      // 修复 base 路径导致的 WebSocket 连接问题
      path: '/@vite/client',
      port: 7003
    },
    proxy: {
      '/api': {
        target: 'http://localhost:8180',
        changeOrigin: true,
        ws: true,  // 启用 WebSocket 代理
        rewrite: (path: string) => path.replace(/^\/api/, '')
      }
    }
  },
  
  build: {
    outDir: 'dist',
    sourcemap: true,
    rollupOptions: {
      output: {
        manualChunks: {
          'vue-vendor': ['vue', 'vue-router', 'pinia'],
          'element-plus': ['element-plus']
        }
      }
    }
  }
}))
