/**
 * Vite Config Generator for React App
 *
 * Generates Vite configuration with React plugin and proxy
 */

import type { TemplateContext } from '@specverse/types';
import { getApiBaseUrl, getPathConfig } from '../../../shared/path-resolver.js';

export default function generateViteConfig(context: TemplateContext): string {
  const { configuration } = context;
  const pathConfig = getPathConfig(context);

  const vitePort = configuration?.vite?.port || 5173;
  const viteHost = configuration?.vite?.host || 'localhost';
  const apiBaseUrl = getApiBaseUrl(pathConfig);
  const apiProxy = configuration?.vite?.proxy?.['/api'] || apiBaseUrl;

  return `import { defineConfig, loadEnv } from 'vite';
import react from '@vitejs/plugin-react';
import path from 'path';

/**
 * Ports and proxy targets are env-overridable via this project's
 * .env (and .env.local). Lets you run several SpecVerse projects
 * side-by-side without port collisions:
 *
 *   # project-a/.env
 *   PORT=3001
 *   VITE_PORT=5174
 *   VITE_API_BASE_URL=http://localhost:3001
 *
 *   # project-b/.env
 *   PORT=3002
 *   VITE_PORT=5175
 *   VITE_API_BASE_URL=http://localhost:3002
 */
export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd(), '');
  const port = Number(env.VITE_PORT ?? ${vitePort});
  const host = env.VITE_HOST ?? '${viteHost}';
  const apiTarget = env.VITE_API_BASE_URL ?? '${apiProxy}';

  return {
    plugins: [react()],
    server: {
      port,
      host,
      proxy: {
        '/api': {
          target: apiTarget,
          changeOrigin: true,
        },
        // WebSocket proxy — the runtime's useEntitySync hook opens
        // ws://<host>/ws to receive entity mutation events from the
        // backend event bus. Without this proxy the socket tries to
        // connect to the vite dev server on /ws and fails, forcing
        // state-sync to fall back to React Query's refetchInterval
        // polling (usable but slow).
        '/ws': {
          target: apiTarget.replace(/^http/, 'ws'),
          ws: true,
          changeOrigin: true,
        },
      },
    },
    build: {
      outDir: 'dist',
      sourcemap: true,
    },
    resolve: {
      alias: {
        '@': path.resolve(__dirname, './src'),
      },
      // Prevent React duplication when using local packages
      dedupe: ['react', 'react-dom'],
    },
  };
});
`;
}
