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

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

  @OnEvent('listing.status_changed', { async: true })
  async handle(event: ListingStatusChangedEvent): Promise<void> {
    this.logger.log(
      `Handling listing.status_changed: ${event.previousStatus} → ${event.newStatus} for ${event.aggregateId}`,
      'ListingStatusChangedHandler',
    );

    // Remove from search index when listing becomes inactive
    const removeStatuses = ['REJECTED', 'EXPIRED', 'SOLD', 'RENTED'];
    if (removeStatuses.includes(event.newStatus)) {
      await this.indexer.removeListing(event.aggregateId);
    }

    // Invalidate caches for any status change
    await Promise.all([
      this.cache.invalidate(CacheService.buildKey(CachePrefix.LISTING, event.aggregateId)),
      this.cache.invalidateByPrefix(CachePrefix.SEARCH),
      this.cache.invalidateByPrefix(CachePrefix.GEO_SEARCH),
    ]);
  }
}
