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

// Get domain from environment (fallback to cmlite.org)
const domain = process.env.DOMAIN || 'cmlite.org';

export default defineConfig({
  plugins: [react()],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src'),
    },
  },
  server: {
    port: 3000,
    host: '0.0.0.0',
    // Allow all hosts — nginx handles Host header validation in production.
    // Vite's allowedHosts only sees the build-time DOMAIN value, which may
    // differ from the runtime domain (e.g., image built for cmlite.org but
    // deployed to wokemail.org).
    allowedHosts: true,
    proxy: {
      '/api': {
        // Use env var with fallback: Docker uses container name, local uses localhost
        target: process.env.VITE_API_URL || 'http://localhost:4000',
        changeOrigin: true,
        ws: true, // WebSocket passthrough for docs collaboration
      },
      '/media/public': {
        // Public media routes: rewrite to /api/public (matches Fastify prefix: '/api')
        target: process.env.VITE_MEDIA_API_URL || 'http://localhost:4100',
        changeOrigin: true,
        rewrite: (p) => p.replace(/^\/media\/public/, '/api/public'),
      },
      '/media': {
        // Media API proxy: other routes (/videos, /reactions) rewrite to /api
        target: process.env.VITE_MEDIA_API_URL || 'http://localhost:4100',
        changeOrigin: true,
        rewrite: (p) => p.replace(/^\/media/, '/api'),
      },
      '/mkdocs-proxy': {
        // Docker: uses VITE_MKDOCS_URL (container networking)
        // Local dev: computes from MKDOCS_PORT in .env (dynamic)
        // Fallback: defaults to 4003 if neither is set
        target: process.env.VITE_MKDOCS_URL ||
          `http://localhost:${process.env.MKDOCS_PORT || '4003'}`,
        changeOrigin: true,
        rewrite: (p) => p.replace(/^\/mkdocs-proxy/, ''),
        ws: true,
      },
    },
  },
});
