import { Injectable } from '@nestjs/common';
import { OnEvent } from '@nestjs/event-emitter';
// eslint-disable-next-line @typescript-eslint/consistent-type-imports -- NestJS DI requires value imports for emitDecoratorMetadata
import { LoggerService, PrismaService } from '@modules/shared';
import { type ReviewDeletedEvent } from '../../domain/events/review-deleted.event';

@Injectable()
export class ReviewDeletedListener {
  constructor(
    private readonly prisma: PrismaService,
    private readonly logger: LoggerService,
  ) {}

  @OnEvent('review.deleted', { async: true })
  async handle(event: ReviewDeletedEvent): Promise<void> {
    this.logger.log(
      `Handling review.deleted: recalculating rating for ${event.targetType}:${event.targetId}`,
      'ReviewDeletedListener',
    );

    // Recalculate average rating for the target (agent)
    const stats = await this.prisma.review.aggregate({
      where: {
        targetType: event.targetType,
        targetId: event.targetId,
      },
      _avg: { rating: true },
      _count: { rating: true },
    });

    const avgRating = stats._avg.rating ?? 0;
    const reviewCount = stats._count.rating;

    // Update the target's cached rating
    if (event.targetType === 'AGENT') {
      await this.prisma.agent.update({
        where: { id: event.targetId },
        data: { qualityScore: avgRating },
      });
    }

    this.logger.log(
      `Rating recalculated for ${event.targetType}:${event.targetId} → avg=${avgRating.toFixed(2)}, count=${reviewCount}`,
      'ReviewDeletedListener',
    );
  }
}
