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 { GetReviewsByUserQuery } from './get-reviews-by-user.query';

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

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