import { ForbiddenException, Inject, NotFoundException } from '@nestjs/common';
import { type IQueryHandler, QueryHandler } from '@nestjs/cqrs';
import { type ReportEntity } from '../../../domain/entities/report.entity';
import { REPORT_REPOSITORY, type IReportRepository } from '../../../domain/repositories/report.repository';
import { GetReportQuery } from './get-report.query';

@QueryHandler(GetReportQuery)
export class GetReportHandler implements IQueryHandler<GetReportQuery, ReportEntity> {
  constructor(
    @Inject(REPORT_REPOSITORY) private readonly reportRepo: IReportRepository,
  ) {}

  async execute(query: GetReportQuery): Promise<ReportEntity> {
    const report = await this.reportRepo.findById(query.reportId);

    if (!report) {
      throw new NotFoundException('Báo cáo không tồn tại.');
    }

    if (report.userId !== query.userId) {
      throw new ForbiddenException('Bạn không có quyền xem báo cáo này.');
    }

    return report;
  }
}
