import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import path from 'path'

export default defineConfig({
  plugins: [react()],
  optimizeDeps: {
    include: ['lucide-react'],
  },
  server: {
    proxy: {
      '/api': {
        target: 'http://localhost:3001',
        changeOrigin: true,
        configure: (proxy) => {
          proxy.on('error', () => {}) // 后端未启动时静默失败
        },
      },
      '/ws': {
        target: 'ws://localhost:3001',
        ws: true,
        changeOrigin: true,
        configure: (proxy) => {
          proxy.on('error', () => {}) // 后端未启动时静默失败
          // 吞掉 ECONNRESET，防止 Vite 打印 "ws proxy socket error"（关标签/刷新时常见）
          function swallowEconnreset(s: { emit?: (ev: string, ...a: unknown[]) => boolean } | null) {
            if (!s?.emit) return
            const orig = s.emit.bind(s)
            s.emit = function (ev: string, ...a: unknown[]) {
              if (ev === 'error' && (a[0] as { code?: string })?.code === 'ECONNRESET') return false
              return orig(ev, ...a)
            }
          }
          proxy.on('proxyReqWs', (proxyReq, _req, socket, _head) => {
            swallowEconnreset(socket ?? null)
            swallowEconnreset((proxyReq as { socket?: unknown })?.socket ?? null)
          })
        },
      },
    },
  },
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src'),
    },
  },
})
