import { Injectable } from '@nestjs/common';
import { CommandBus } from '@nestjs/cqrs';
import { OnEvent } from '@nestjs/event-emitter';
import { SendNotificationCommand } from '@modules/notifications';
import { LoggerService, PrismaService } from '@modules/shared';
import { type UserBannedEvent } from '../../domain/events/user-banned.event';

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

  @OnEvent('user.banned', { async: true })
  async handle(event: UserBannedEvent): Promise<void> {
    this.logger.log(`Handling user.banned for user ${event.aggregateId}`, 'UserBannedListener');

    // Deactivate all active listings belonging to the banned user
    const deactivated = await this.prisma.listing.updateMany({
      where: {
        sellerId: event.aggregateId,
        status: { in: ['ACTIVE', 'PENDING_REVIEW', 'DRAFT'] },
      },
      data: { status: 'EXPIRED' },
    });

    this.logger.log(
      `Deactivated ${deactivated.count} listings for banned user ${event.aggregateId}`,
      'UserBannedListener',
    );

    // Notify the banned user via email
    const user = await this.prisma.user.findUnique({
      where: { id: event.aggregateId },
      select: { id: true, email: true },
    });

    if (user?.email) {
      await this.commandBus.execute(
        new SendNotificationCommand(
          user.id,
          'EMAIL',
          'user.banned',
          { reason: event.reason },
          user.email,
        ),
      );
    }
  }
}
