import { fileURLToPath, URL } from 'node:url'

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

// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
  // Load all env vars (no VITE_ prefix filter) so dev-server-only keys are readable here.
  const env = loadEnv(mode, process.cwd(), '')

  const host = env.VITE_DEV_HOST || '0.0.0.0'
  const port = Number(env.VITE_DEV_PORT) || 5173

  // "all" allows any host; otherwise split the comma-separated list into a string[].
  const allowedHostsRaw = env.VITE_DEV_ALLOWED_HOSTS || 'localhost,127.0.0.1'
  const allowedHosts =
    allowedHostsRaw.trim() === 'all'
      ? true
      : allowedHostsRaw
          .split(',')
          .map((h) => h.trim())
          .filter((h) => h.length > 0)

  // Optional /api dev proxy: enabled only when VITE_DEV_PROXY_TARGET is non-empty.
  const proxyTarget = env.VITE_DEV_PROXY_TARGET?.trim()
  const proxy = proxyTarget ? { '/api': { target: proxyTarget, changeOrigin: true } } : undefined

  return {
    plugins: [react()],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
      },
    },
    server: {
      host,
      port,
      allowedHosts,
      proxy,
    },
  }
})
