import { EventsHandler, type IEventHandler } from '@nestjs/cqrs';
import { PrismaService, LoggerService } from '@modules/shared';
import { ListingPriceChangedEvent } from '../../domain/events/listing-price-changed.event';

@EventsHandler(ListingPriceChangedEvent)
export class RecordPriceHistoryHandler implements IEventHandler<ListingPriceChangedEvent> {
  constructor(
    private readonly prisma: PrismaService,
    private readonly logger: LoggerService,
  ) {}

  async handle(event: ListingPriceChangedEvent): Promise<void> {
    try {
      await this.prisma.priceHistory.create({
        data: {
          listingId: event.aggregateId,
          oldPrice: event.oldPrice,
          newPrice: event.newPrice,
          source: event.source,
          changedAt: event.occurredAt,
        },
      });

      this.logger.debug(
        `Recorded price change for listing ${event.aggregateId}: ${event.oldPrice} → ${event.newPrice}`,
        'RecordPriceHistoryHandler',
      );
    } catch (err) {
      this.logger.error(
        `Failed to record price history for listing ${event.aggregateId}: ${(err as Error).message}`,
        (err as Error).stack,
        'RecordPriceHistoryHandler',
      );
    }
  }
}
