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

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

  @OnEvent('listing.approved_by_admin', { async: true })
  async handle(event: ListingApprovedEvent): Promise<void> {
    this.logger.log(`Handling listing.approved_by_admin for ${event.aggregateId}`, 'ListingApprovedListener');

    const listing = await this.prisma.listing.findUnique({
      where: { id: event.aggregateId },
      include: {
        property: { select: { title: true } },
        seller: { select: { id: true, email: true } },
      },
    });

    if (!listing?.seller.email) return;

    await this.commandBus.execute(
      new SendNotificationCommand(
        listing.seller.id,
        'EMAIL',
        'listing.approved',
        { listingTitle: listing.property.title },
        listing.seller.email,
      ),
    );
  }
}
