import { Injectable } from "@nestjs/common";
import type { McpTool } from "./interfaces";

/**
 * Service for managing MCP tool registry
 * Maintains catalog of tools provided by MCP servers
 */
@Injectable()
export class ToolRegistryService {
  private tools = new Map<string, McpTool>();

  /**
   * Register a tool from an MCP server
   */
  registerTool(tool: McpTool): void {
    this.tools.set(tool.name, tool);
  }

  /**
   * Unregister a tool
   */
  unregisterTool(toolName: string): void {
    this.tools.delete(toolName);
  }

  /**
   * Get tool by name
   */
  getTool(name: string): McpTool | undefined {
    return this.tools.get(name);
  }

  /**
   * List all registered tools
   */
  listTools(): McpTool[] {
    return Array.from(this.tools.values());
  }

  /**
   * List tools provided by a specific server
   */
  listToolsByServer(serverId: string): McpTool[] {
    return Array.from(this.tools.values()).filter((tool) => tool.serverId === serverId);
  }

  /**
   * Clear all tools for a server
   */
  clearServerTools(serverId: string): void {
    const toolsToRemove = Array.from(this.tools.values())
      .filter((tool) => tool.serverId === serverId)
      .map((tool) => tool.name);

    for (const toolName of toolsToRemove) {
      this.tools.delete(toolName);
    }
  }
}
