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

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

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

    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.rejected',
        { listingTitle: listing.property.title, reason: event.reason },
        listing.seller.email,
      ),
    );
  }
}
