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

// Proxy /api → be0 (locally :4402; in Docker set VITE_DEV_PROXY_TARGET=http://be0:4402).
const apiProxyTarget = process.env.VITE_DEV_PROXY_TARGET || 'http://localhost:4402';
// Vite 5 checks the Host header; allow all when VITE_ALLOWED_HOSTS is unset, else the list.
const allowedHosts = (process.env.VITE_ALLOWED_HOSTS ?? '')
  .split(',')
  .map((h) => h.trim())
  .filter(Boolean);

export default defineConfig(({ mode }) => ({
  server: {
    host: '0.0.0.0',
    port: 5174,
    allowedHosts: allowedHosts.length > 0 ? allowedHosts : true,
    proxy: {
      '/api': { target: apiProxyTarget, changeOrigin: true, secure: false },
      '/submitted-initiatives': { target: apiProxyTarget, changeOrigin: true, secure: false },
    },
  },
  plugins: [react()],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src'),
      // Consume the shared kernel as source (no build step) — Vite transpiles it.
      '@ump/shared': path.resolve(__dirname, '../shared/src/index.ts'),
    },
  },
  build: {
    // Never ship source maps — keeps the original TypeScript un-reconstructable in DevTools.
    sourcemap: false,
  },
  esbuild: {
    // Strip console/debugger from production bundles so no debug/internal info leaks.
    drop: mode === 'production' ? ['console', 'debugger'] : [],
  },
}));
