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 { ReindexAllCommand } from './reindex-all.command';

export interface ReindexResult {
  indexed: number;
  total: number;
}

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

  async execute(): Promise<ReindexResult> {
    try {
      return this.indexer.reindexAll();
    } catch (error) {
      if (error instanceof DomainException) throw error;
      this.logger.error(
        `Failed to reindex all listings: ${error instanceof Error ? error.message : error}`,
        error instanceof Error ? error.stack : undefined,
        this.constructor.name,
      );
      throw new InternalServerErrorException('Không thể đánh chỉ mục lại toàn bộ danh sách');
    }
  }
}
