/**
 * Matrix Vite Config Factory — generates a correct vite.config.ts for any Matrix webapp.
 *
 * Usage in your app's vite.config.ts:
 *   import { createMatrixViteConfig } from '@open-matrix/browser-kit/vite';
 *   export default createMatrixViteConfig({ appName: 'harness' });
 */

import { defineConfig, loadEnv } from 'vite';
import { resolve, dirname } from 'path';

export interface MatrixViteConfigOptions {
  appName: string;
  root?: string;
  outDir?: string;
  daemonPort?: number;
  extraAliases?: Record<string, string>;
  extraExternals?: string[];
}

export function createMatrixViteConfig(options: MatrixViteConfigOptions, callerDir: string) {
  const {
    appName,
    root = 'src',
    outDir = 'dist',
    daemonPort = 3100,
  } = options;

  const browserKitShims = resolve(dirname(new URL(import.meta.url).pathname), '../shims');

  return defineConfig(({ command, mode }) => {
    const env = loadEnv(mode, callerDir, '');
    const daemonOrigin = (env.MATRIX_DAEMON_ORIGIN || `http://127.0.0.1:${daemonPort}`).replace(/\/$/, '');

    return {
      root: resolve(callerDir, root),
      publicDir: false,
      base: `/apps/${appName}/`,
      build: {
        outDir: resolve(callerDir, outDir),
        emptyOutDir: true,
        rollupOptions: {
          input: resolve(callerDir, root, 'index.html'),
        },
        target: 'es2022',
        chunkSizeWarningLimit: 800,
      },
      resolve: {
        alias: {
          '@open-matrix/core': resolve(browserKitShims, 'open-matrix-core.ts'),
          crypto: resolve(browserKitShims, 'crypto.ts'),
          'node:crypto': resolve(browserKitShims, 'crypto.ts'),
          child_process: resolve(browserKitShims, 'child_process.ts'),
          'node:child_process': resolve(browserKitShims, 'child_process.ts'),
          'fs/promises': resolve(browserKitShims, 'fs-promises.ts'),
          'node:fs/promises': resolve(browserKitShims, 'fs-promises.ts'),
          fs: resolve(browserKitShims, 'fs.ts'),
          'node:fs': resolve(browserKitShims, 'fs.ts'),
          path: resolve(browserKitShims, 'path.ts'),
          'node:path': resolve(browserKitShims, 'path.ts'),
          ...options.extraAliases,
        },
      },
      ...(command === 'serve'
        ? {
            server: {
              proxy: {
                '/.matrix': { target: daemonOrigin, changeOrigin: true },
                '/api': { target: daemonOrigin, changeOrigin: true },
                '/auth': { target: daemonOrigin, changeOrigin: true },
                '/login': { target: daemonOrigin, changeOrigin: true },
                '/logout': { target: daemonOrigin, changeOrigin: true },
                '/healthz': { target: daemonOrigin, changeOrigin: true },
                '/nats-ws': { target: daemonOrigin, changeOrigin: true, ws: true },
              },
            },
          }
        : {}),
    };
  });
}
