import { Injectable } from '@nestjs/common';
import { OnEvent } from '@nestjs/event-emitter';
import { type ListingFeaturedExpiredEvent } from '@modules/listings';
import { CacheService, CachePrefix, LoggerService } from '@modules/shared';
import { ListingIndexerService } from '../services/listing-indexer.service';

@Injectable()
export class ListingFeaturedExpiredHandler {
  constructor(
    private readonly indexer: ListingIndexerService,
    private readonly cache: CacheService,
    private readonly logger: LoggerService,
  ) {}

  @OnEvent('listing.featured_expired', { async: true })
  async handle(event: ListingFeaturedExpiredEvent): Promise<void> {
    this.logger.log(
      `Handling listing.featured_expired for ${event.aggregateId}`,
      'ListingFeaturedExpiredHandler',
    );

    // Re-index to clear the isFeatured boost in Typesense
    await Promise.all([
      this.indexer.indexListing(event.aggregateId),
      this.cache.invalidate(CacheService.buildKey(CachePrefix.LISTING, event.aggregateId)),
      this.cache.invalidateByPrefix(CachePrefix.SEARCH),
      this.cache.invalidateByPrefix(CachePrefix.GEO_SEARCH),
    ]);
  }
}
