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

export default defineConfig({
  plugins: [react()],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src'),
    },
  },
  server: {
    port: 5173,
    proxy: {
      // Booterm runs on a separate port (9501 in compose). Order matters:
      // /api/term/* and /ws/term/* must be listed before the broader /api
      // entry so Vite matches the more specific prefix first.
      '/api/term': {
        target: process.env.BOOTERM_DEV_URL ?? 'http://127.0.0.1:9501',
        changeOrigin: true,
        headers: {
          'Remote-User': process.env.DEV_REMOTE_USER ?? 'sam',
        },
      },
      '/ws/term': {
        target: process.env.BOOTERM_DEV_URL ?? 'http://127.0.0.1:9501',
        changeOrigin: true,
        ws: true,
        headers: {
          'Remote-User': process.env.DEV_REMOTE_USER ?? 'sam',
        },
      },
      // BooCoder: proxy /api/coder/* to the coder container. Must be listed
      // before /api so the more-specific prefix matches first.
      '/api/coder': {
        target: process.env.BOOCODER_DEV_URL ?? 'http://127.0.0.1:9502',
        changeOrigin: true,
        ws: true,
        rewrite: (path: string) => path.replace(/^\/api\/coder/, '/api'),
        headers: {
          'Remote-User': process.env.DEV_REMOTE_USER ?? 'sam',
        },
      },
      '/api': {
        target: 'http://127.0.0.1:3000',
        changeOrigin: true,
        ws: true,
        headers: {
          'Remote-User': process.env.DEV_REMOTE_USER ?? 'sam',
        },
      },
    },
  },
  build: {
    outDir: 'dist',
    emptyOutDir: true,
  },
});
