import { Inject, InternalServerErrorException } from '@nestjs/common';
import { QueryHandler, type IQueryHandler } from '@nestjs/cqrs';
import { DomainException, LoggerService } from '@modules/shared';
import { type ListingSearchItem } from '../../../domain/repositories/listing-read.dto';
import { LISTING_REPOSITORY, type IListingRepository, type PaginatedResult } from '../../../domain/repositories/listing.repository';
import { GetPendingModerationQuery } from './get-pending-moderation.query';

@QueryHandler(GetPendingModerationQuery)
export class GetPendingModerationHandler implements IQueryHandler<GetPendingModerationQuery> {
  constructor(
    @Inject(LISTING_REPOSITORY) private readonly listingRepo: IListingRepository,
    private readonly logger: LoggerService,
  ) {}

  async execute(query: GetPendingModerationQuery): Promise<PaginatedResult<ListingSearchItem>> {
    try {
      return this.listingRepo.findByStatus('PENDING_REVIEW', query.page, query.limit);
    } catch (error) {
      if (error instanceof DomainException) throw error;
      this.logger.error(
        `Failed to get pending moderation listings: ${error instanceof Error ? error.message : error}`,
        error instanceof Error ? error.stack : undefined,
        this.constructor.name,
      );
      throw new InternalServerErrorException('Không thể lấy danh sách tin đăng chờ kiểm duyệt');
    }
  }
}
