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

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

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

    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.renewed',
        {
          planTier: event.planTier,
          periodEnd: event.newPeriodEnd.toISOString(),
        },
        user.email,
      ),
    );
  }
}
