/**
 * Catch-all proxy route that forwards /api/v1/* requests to mcpd.
 */
import type { FastifyInstance } from 'fastify';
import { AuthenticationError, ConnectionError } from '../mcpd-client.js';
import type { McpdClient } from '../mcpd-client.js';

export function registerProxyRoutes(app: FastifyInstance, client: McpdClient): void {
  app.all('/api/v1/*', async (request, reply) => {
    const path = (request.url.split('?')[0]) ?? '/';
    const querystring = request.url.includes('?')
      ? request.url.slice(request.url.indexOf('?') + 1)
      : '';

    const body = request.method !== 'GET' && request.method !== 'HEAD'
      ? (request.body as unknown)
      : undefined;

    // Forward the user's auth token to mcpd so RBAC applies per-user.
    // If no user token is present, mcpd will use its auth hook to reject.
    const authHeader = request.headers['authorization'] as string | undefined;
    const userToken = authHeader?.startsWith('Bearer ') ? authHeader.slice(7) : undefined;

    try {
      const result = await client.forward(request.method, path, querystring, body, userToken);
      return reply.code(result.status).send(result.body);
    } catch (err: unknown) {
      if (err instanceof AuthenticationError) {
        return reply.code(401).send({
          error: 'unauthorized',
          message: 'Authentication with mcpd failed. Run `mcpctl login` to refresh your token.',
        });
      }
      if (err instanceof ConnectionError) {
        return reply.code(503).send({
          error: 'service_unavailable',
          message: 'Cannot reach mcpd daemon. Is it running?',
        });
      }
      throw err;
    }
  });
}
