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

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

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

    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.expired',
        { planTier: event.planTier },
        user.email,
      ),
    );
  }
}
