import { Module, type OnModuleInit } from '@nestjs/common';
import { CqrsModule } from '@nestjs/cqrs';
import { type LoggerService } from '@modules/shared';
import { ReindexAllHandler } from './application/commands/reindex-all/reindex-all.handler';
import { SyncListingHandler } from './application/commands/sync-listing/sync-listing.handler';
import { GeoSearchHandler } from './application/queries/geo-search/geo-search.handler';
import { SearchPropertiesHandler } from './application/queries/search-properties/search-properties.handler';
import { SEARCH_REPOSITORY } from './domain/repositories/search.repository';
import { ListingApprovedEventHandler } from './infrastructure/event-handlers/listing-approved.handler';
import { ListingStatusChangedHandler } from './infrastructure/event-handlers/listing-status-changed.handler';
import { ListingIndexerService } from './infrastructure/services/listing-indexer.service';
import { TypesenseClientService } from './infrastructure/services/typesense-client.service';
import { TypesenseSearchRepository } from './infrastructure/services/typesense-search.repository';
import { SearchController } from './presentation/controllers/search.controller';

const CommandHandlers = [SyncListingHandler, ReindexAllHandler];
const QueryHandlers = [SearchPropertiesHandler, GeoSearchHandler];

@Module({
  imports: [CqrsModule],
  controllers: [SearchController],
  providers: [
    // Infrastructure
    TypesenseClientService,
    TypesenseSearchRepository,
    { provide: SEARCH_REPOSITORY, useExisting: TypesenseSearchRepository },
    ListingIndexerService,

    // Event handlers
    ListingApprovedEventHandler,
    ListingStatusChangedHandler,

    // CQRS
    ...CommandHandlers,
    ...QueryHandlers,
  ],
  exports: [ListingIndexerService, SEARCH_REPOSITORY, TypesenseClientService],
})
export class SearchModule implements OnModuleInit {
  constructor(
    private readonly typesenseClient: TypesenseClientService,
    private readonly searchRepo: TypesenseSearchRepository,
    private readonly logger: LoggerService,
  ) {}

  async onModuleInit(): Promise<void> {
    try {
      await this.searchRepo.ensureCollection();
      this.logger.log('Search module initialized — Typesense collection ready', 'SearchModule');
    } catch (err) {
      this.logger.error(
        `Failed to initialize Typesense collection: ${err instanceof Error ? err.message : String(err)}`,
        'SearchModule',
      );
    }
  }
}
