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

// https://vite.dev/config/
export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd(), '')
  // Must match `PORT` / `APP_PORT` for `combined-server.mjs` (see SAT_backend/.env or root .env).
  const apiTarget = (env.VITE_DEV_API_PROXY_TARGET || 'http://localhost:5012').replace(/\/+$/, '')

  return {
    plugins: [react()],
    build: {
      rollupOptions: {
        output: {
          manualChunks(id) {
            if (id.includes('node_modules/react-dom') || id.includes('node_modules/react/')) {
              return 'react-vendor';
            }
            if (id.includes('node_modules/recharts')) {
              return 'chart-vendor';
            }
          },
        },
      },
    },
    server: {
      proxy: {
        // Same-origin /api in dev → avoids CORS on fetch() (JSON + snap images with Bearer).
        // Point at your ORAC Risk Assessment API (must match APP_PORT / JWT secrets).
        '/api': {
          target: apiTarget,
          changeOrigin: true
        },
        '/uploads': {
          target: apiTarget,
          changeOrigin: true
        }
      }
    }
  }
})
