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

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

  @OnEvent('subscription.cancelled', { async: true })
  async handle(event: SubscriptionCancelledEvent): Promise<void> {
    this.logger.log(`Handling subscription.cancelled for ${event.aggregateId}`, 'SubscriptionExpiringListener');

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

    if (!user?.email) return;

    await this.commandBus.execute(
      new SendNotificationCommand(
        event.userId,
        'EMAIL',
        'subscription.expiring',
        { planTier: event.planTier },
        user.email,
      ),
    );
  }
}
