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

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

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

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

    if (!listing) return;

    // Notify the seller
    if (listing.seller.email) {
      await this.commandBus.execute(
        new SendNotificationCommand(
          listing.seller.id,
          'EMAIL',
          'listing.sold',
          { listingTitle: listing.property.title, finalStatus: event.finalStatus },
          listing.seller.email,
        ),
      );
    }

    this.logger.log(
      `Notified seller for listing ${event.aggregateId}`,
      'ListingSoldListener',
    );
  }
}
