import { McpModule as McpCoreModule, McpRegistryService } from '@goodgo/mcp-servers';
import { Module, type OnModuleInit } from '@nestjs/common';
import { AuthModule } from '@modules/auth';
import { SearchModule, TypesenseClientService } from '@modules/search';
import { LoggerService } from '@modules/shared';
import { McpTransportController } from './presentation/mcp-transport.controller';

@Module({
  imports: [
    SearchModule,
    AuthModule,
    McpCoreModule.forRoot({
      aiServiceBaseUrl: process.env['AI_SERVICE_URL'] || 'http://localhost:8000',
      apiBaseUrl: process.env['API_BASE_URL'] || 'http://localhost:3001/api/v1',
      typesenseCollectionName: 'listings',
      skipDefaultController: true,
    }),
  ],
  controllers: [McpTransportController],
})
export class McpIntegrationModule implements OnModuleInit {
  constructor(
    private readonly typesenseClient: TypesenseClientService,
    private readonly mcpRegistry: McpRegistryService,
    private readonly logger: LoggerService,
  ) {}

  async onModuleInit(): Promise<void> {
    this.mcpRegistry.setTypesenseClient(this.typesenseClient.getClient());

    // Re-initialize servers now that Typesense client is available
    await this.mcpRegistry.onModuleInit();

    const servers = this.mcpRegistry.getServerNames();
    this.logger.log(
      `MCP servers initialized: ${servers.join(', ')}`,
      'McpIntegrationModule',
    );
  }
}
