import type { GatewayRequest, OutboundMessage } from '../protocol.js';
import { makeResponse, makeError, ErrorCode } from '../protocol.js';
import type { ToolRegistry } from '../../tools/registry.js';
import type { ToolExecutor } from '../../tools/executor.js';

export interface ToolHandlerDeps {
  toolRegistry: ToolRegistry;
  toolExecutor: ToolExecutor;
}

export function createToolHandlers(deps: ToolHandlerDeps) {
  return {
    'tools.list': async (request: GatewayRequest): Promise<OutboundMessage> => {
      // Use filteredList to respect tool policy (gateway context has no agent/provider)
      const tools = deps.toolRegistry.filteredList().map(t => ({
        name: t.name,
        description: t.description,
        inputSchema: t.inputSchema,
      }));
      return makeResponse(request.id, { tools });
    },

    'tools.invoke': async (request: GatewayRequest): Promise<OutboundMessage> => {
      const params = request.params as { tool?: string; args?: Record<string, unknown> } | undefined;
      if (!params?.tool) {
        return makeError(request.id, ErrorCode.InvalidRequest, 'tool name is required');
      }

      const tool = deps.toolRegistry.get(params.tool);
      if (!tool) {
        return makeError(request.id, ErrorCode.ToolNotFound, `Tool not found: ${params.tool}`);
      }

      // Pass no context — gateway uses global policy only
      const result = await deps.toolExecutor.execute(params.tool, params.args ?? {});
      return makeResponse(request.id, result);
    },
  };
}
