import { Inject, InternalServerErrorException } from '@nestjs/common';
import { type IQueryHandler, QueryHandler } from '@nestjs/cqrs';
import { DomainException, LoggerService } from '@modules/shared';
import { type ReviewStatsData } from '../../../domain/repositories/review-read.dto';
import { REVIEW_REPOSITORY, type IReviewRepository } from '../../../domain/repositories/review.repository';
import { GetAverageRatingQuery } from './get-average-rating.query';

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

  async execute(query: GetAverageRatingQuery): Promise<ReviewStatsData> {
    try {
      return await this.reviewRepo.getStats(query.targetType, query.targetId);
    } catch (error) {
      if (error instanceof DomainException) throw error;
      this.logger.error(
        `Failed to get average rating: ${error instanceof Error ? error.message : String(error)}`,
        error instanceof Error ? error.stack : undefined,
        'GetAverageRatingHandler',
      );
      throw new InternalServerErrorException('Lỗi khi lấy đánh giá trung bình');
    }
  }
}
