import { Injectable } from '@nestjs/common';
import { CommandBus } from '@nestjs/cqrs';
import { OnEvent } from '@nestjs/event-emitter';
import { LoggerService, PrismaService } from '@modules/shared';
import { type QuotaExceededEvent } from '@modules/subscriptions';
import { SendNotificationCommand } from '../commands/send-notification/send-notification.command';

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

  @OnEvent('quota.exceeded', { async: true })
  async handle(event: QuotaExceededEvent): Promise<void> {
    this.logger.log(
      `Handling quota.exceeded for user=${event.aggregateId}, metric=${event.metric}`,
      'QuotaExceededListener',
    );

    const user = await this.prisma.user.findUnique({
      where: { id: event.aggregateId },
      select: { id: true, email: true },
    });

    if (!user?.email) return;

    await this.commandBus.execute(
      new SendNotificationCommand(
        user.id,
        'EMAIL',
        'quota.exceeded',
        {
          metric: event.metric,
          limit: event.limit,
          used: event.used,
        },
        user.email,
      ),
    );
  }
}
