import { Inject, InternalServerErrorException } from '@nestjs/common';
import { type IQueryHandler, QueryHandler } from '@nestjs/cqrs';
import { DomainException, LoggerService } from '@modules/shared';
import { type ReviewItemData } from '../../../domain/repositories/review-read.dto';
import { REVIEW_REPOSITORY, type IReviewRepository, type PaginatedResult } from '../../../domain/repositories/review.repository';
import { GetReviewsByTargetQuery } from './get-reviews-by-target.query';

@QueryHandler(GetReviewsByTargetQuery)
export class GetReviewsByTargetHandler implements IQueryHandler<GetReviewsByTargetQuery> {
  constructor(
    @Inject(REVIEW_REPOSITORY) private readonly reviewRepo: IReviewRepository,
    private readonly logger: LoggerService,
  ) {}

  async execute(query: GetReviewsByTargetQuery): Promise<PaginatedResult<ReviewItemData>> {
    try {
      return await this.reviewRepo.findByTarget(
        query.targetType,
        query.targetId,
        query.page,
        query.limit,
      );
    } catch (error) {
      if (error instanceof DomainException) throw error;
      this.logger.error(
        `Failed to get reviews by target: ${error instanceof Error ? error.message : String(error)}`,
        error instanceof Error ? error.stack : undefined,
        'GetReviewsByTargetHandler',
      );
      throw new InternalServerErrorException('Lỗi khi lấy danh sách đánh giá');
    }
  }
}
