import { Injectable } from '@nestjs/common';
import { CommandBus } from '@nestjs/cqrs';
import { OnEvent } from '@nestjs/event-emitter';
import { LoggerService } from '@modules/shared';
import { RecalculateQualityScoreCommand } from '../commands/recalculate-quality-score/recalculate-quality-score.command';

@Injectable()
export class ReviewEventsListener {
  constructor(
    private readonly commandBus: CommandBus,
    private readonly logger: LoggerService,
  ) {}

  @OnEvent('review.created', { async: true })
  async onReviewCreated(event: {
    targetType: string;
    targetId: string;
  }): Promise<void> {
    if (event.targetType === 'AGENT') {
      this.logger.log(
        `Recalculating quality score for agent ${event.targetId}`,
        'ReviewEventsListener',
      );
      await this.commandBus.execute(
        new RecalculateQualityScoreCommand(event.targetId),
      );
    }
  }

  @OnEvent('review.deleted', { async: true })
  async onReviewDeleted(event: {
    targetType: string;
    targetId: string;
  }): Promise<void> {
    if (event.targetType === 'AGENT') {
      this.logger.log(
        `Recalculating quality score for agent ${event.targetId} after review deletion`,
        'ReviewEventsListener',
      );
      await this.commandBus.execute(
        new RecalculateQualityScoreCommand(event.targetId),
      );
    }
  }
}
