import { InternalServerErrorException } from '@nestjs/common';
import { CommandHandler, type ICommandHandler } from '@nestjs/cqrs';
import { DomainException, LoggerService } from '@modules/shared';
import { ListingIndexerService } from '../../../infrastructure/services/listing-indexer.service';
import { SyncListingCommand } from './sync-listing.command';

@CommandHandler(SyncListingCommand)
export class SyncListingHandler implements ICommandHandler<SyncListingCommand> {
  constructor(
    private readonly indexer: ListingIndexerService,
    private readonly logger: LoggerService,
  ) {}

  async execute(command: SyncListingCommand): Promise<void> {
    try {
      await this.indexer.indexListing(command.listingId);
    } catch (error) {
      if (error instanceof DomainException) throw error;
      this.logger.error(
        `Failed to sync listing ${command.listingId}: ${error instanceof Error ? error.message : error}`,
        error instanceof Error ? error.stack : undefined,
        this.constructor.name,
      );
      throw new InternalServerErrorException('Không thể đồng bộ tin đăng vào chỉ mục tìm kiếm');
    }
  }
}
