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

// M13b W0: vite dev proxies /v1/* to the local stack:
//   /v1/auth/* → authd   (port 8804)
//   /v1/*      → admind  (port 8803)
//
// In production, the SPA is embedded in admind and served from /,
// so all /v1/* requests go to the same origin (admind).
const devProxies = (() => {
  const authd = process.env.VITE_PROXY_AUTHD ?? 'http://127.0.0.1:8804';
  const admind = process.env.VITE_PROXY_ADMIND ?? 'http://127.0.0.1:8803';
  return [
    {
      context: ['/v1/auth', '/health'],
      target: authd,
      changeOrigin: false,
    },
    {
      context: ['/v1'],
      target: admind,
      changeOrigin: false,
    },
  ];
})();

export default defineConfig({
  plugins: [react()],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, 'src'),
    },
  },
  server: {
    port: 5173,
    proxy: devProxies,
  },
  build: {
    outDir: process.env.VITE_OUT_DIR ?? '../cmd/admind/web-dist',
    emptyOutDir: true,
    sourcemap: false,
    target: 'es2022',
    rollupOptions: {
      output: {
        manualChunks: {
          react: ['react', 'react-dom', 'react-router-dom'],
          query: ['@tanstack/react-query'],
          forms: ['react-hook-form', '@hookform/resolvers', 'zod'],
          ui: ['lucide-react', 'sonner'],
        },
      },
    },
  },
});
