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

@Module({
  imports: [
    SearchModule,
    AuthModule,
    McpCoreModule.forRoot({
      aiServiceBaseUrl: process.env['AI_SERVICE_URL'] || 'http://localhost:8000',
      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',
    );
  }
}
