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

export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd(), '')
  const allowedHost = env.VITE_ALLOWED_HOST || 'prof.open-squared.tech'
  const proxyTarget = env.VITE_DEV_API_PROXY_TARGET || 'http://backend:8000'
  const hmrHost = env.VITE_HMR_HOST
  const hmrProtocol = env.VITE_HMR_PROTOCOL
  const hmrClientPort = env.VITE_HMR_CLIENT_PORT ? Number(env.VITE_HMR_CLIENT_PORT) : undefined

  return {
    plugins: [react()],
    server: {
      host: true,
      allowedHosts: [allowedHost],
      proxy: {
        '/api': {
          target: proxyTarget,
          changeOrigin: true,
        },
      },
      hmr: hmrHost
        ? {
            host: hmrHost,
            protocol: hmrProtocol || 'ws',
            clientPort: hmrClientPort,
          }
        : undefined,
    },
  }
})
