import type { FastifyInstance } from 'fastify';
import type { McpProxyService } from '../services/mcp-proxy-service.js';
import type { AuditLogService } from '../services/audit-log.service.js';
import { createAuthMiddleware, type AuthDeps } from '../middleware/auth.js';

export interface McpProxyRouteDeps {
  mcpProxyService: McpProxyService;
  auditLogService: AuditLogService;
  authDeps: AuthDeps;
}

export function registerMcpProxyRoutes(app: FastifyInstance, deps: McpProxyRouteDeps): void {
  const authMiddleware = createAuthMiddleware(deps.authDeps);

  app.post<{
    Body: {
      serverId: string;
      method: string;
      params?: Record<string, unknown>;
    };
  }>('/api/v1/mcp/proxy', { preHandler: [authMiddleware] }, async (request) => {
    const { serverId, method, params } = request.body;

    const result = await deps.mcpProxyService.execute({ serverId, method, params });

    // Log to audit with userId (set by auth middleware)
    await deps.auditLogService.create({
      userId: request.userId!,
      action: 'MCP_PROXY',
      resource: 'mcp-server',
      resourceId: serverId,
      details: { method, hasParams: params !== undefined },
    });

    return result;
  });
}
