import { Router } from 'express';
import { DataSource } from 'typeorm';
import { McpServerService, ToolRegistryService, ToolLoggerService } from './services';
import { McpController } from './controllers';
import { ToolCall, ToolCallResult } from './entities';
import {
  ProductsToolsService,
  InventoryToolsService,
  OrdersToolsService,
  CustomersToolsService,
  FiadosToolsService,
  SalesToolsService,
  FinancialToolsService,
  BranchToolsService,
} from './tools';

export interface McpModuleOptions {
  dataSource: DataSource;
  basePath?: string;
}

export class McpModule {
  public router: Router;
  public mcpService: McpServerService;
  public toolRegistry: ToolRegistryService;
  private dataSource: DataSource;
  private basePath: string;

  constructor(options: McpModuleOptions) {
    this.dataSource = options.dataSource;
    this.basePath = options.basePath || '';
    this.router = Router();
    this.initializeServices();
    this.initializeRoutes();
  }

  private initializeServices(): void {
    // Repositories
    const toolCallRepository = this.dataSource.getRepository(ToolCall);
    const toolCallResultRepository = this.dataSource.getRepository(ToolCallResult);

    // Tool Logger
    const toolLogger = new ToolLoggerService(toolCallRepository, toolCallResultRepository);

    // Tool Registry
    this.toolRegistry = new ToolRegistryService();

    // Register tool providers
    this.toolRegistry.registerProvider(new ProductsToolsService());
    this.toolRegistry.registerProvider(new InventoryToolsService());
    this.toolRegistry.registerProvider(new OrdersToolsService());
    this.toolRegistry.registerProvider(new CustomersToolsService());
    this.toolRegistry.registerProvider(new FiadosToolsService());
    this.toolRegistry.registerProvider(new SalesToolsService());
    this.toolRegistry.registerProvider(new FinancialToolsService());
    this.toolRegistry.registerProvider(new BranchToolsService());

    // MCP Server Service
    this.mcpService = new McpServerService(this.toolRegistry, toolLogger);
  }

  private initializeRoutes(): void {
    const mcpController = new McpController(this.mcpService);
    this.router.use(`${this.basePath}/mcp`, mcpController.router);
  }

  static getEntities(): Function[] {
    return [ToolCall, ToolCallResult];
  }
}
