import { Injectable } from '@nestjs/common';
import { OnEvent } from '@nestjs/event-emitter';
import { LoggerService } from '@modules/shared';
import { type TransferListingCreatedEvent } from '../../domain/events/transfer-listing-created.event';
import { type TransferListingUpdatedEvent } from '../../domain/events/transfer-listing-updated.event';
import { type TransferListingDeletedEvent } from '../../domain/events/transfer-listing-deleted.event';
import { TypesenseTransferService } from '../services/typesense-transfer.service';

@Injectable()
export class TransferListingTypesenseHandler {
  constructor(
    private readonly typesense: TypesenseTransferService,
    private readonly logger: LoggerService,
  ) {}

  @OnEvent('transfer_listing.created', { async: true })
  async handleCreated(event: TransferListingCreatedEvent): Promise<void> {
    this.logger.log(
      `Handling transfer_listing.created for ${event.aggregateId}`,
      'TransferListingTypesenseHandler',
    );
    await this.typesense.indexListing(event.aggregateId);
  }

  @OnEvent('transfer_listing.updated', { async: true })
  async handleUpdated(event: TransferListingUpdatedEvent): Promise<void> {
    this.logger.log(
      `Handling transfer_listing.updated for ${event.aggregateId}`,
      'TransferListingTypesenseHandler',
    );
    await this.typesense.indexListing(event.aggregateId);
  }

  @OnEvent('transfer_listing.deleted', { async: true })
  async handleDeleted(event: TransferListingDeletedEvent): Promise<void> {
    this.logger.log(
      `Handling transfer_listing.deleted for ${event.aggregateId}`,
      'TransferListingTypesenseHandler',
    );
    await this.typesense.deleteListing(event.aggregateId);
  }
}
