import { Inject } from '@nestjs/common';
import { type ICommandHandler, CommandHandler } from '@nestjs/cqrs';
import { EventBusService, NotFoundException } from '@modules/shared';
import { TransferListingUpdatedEvent } from '../../../domain/events';
import {
  TRANSFER_LISTING_REPOSITORY,
  type ITransferListingRepository,
} from '../../../domain/repositories/transfer-listing.repository';
import { ModerateTransferListingCommand } from './moderate-transfer-listing.command';

@CommandHandler(ModerateTransferListingCommand)
export class ModerateTransferListingHandler implements ICommandHandler<ModerateTransferListingCommand> {
  constructor(
    @Inject(TRANSFER_LISTING_REPOSITORY)
    private readonly repo: ITransferListingRepository,
    private readonly eventBus: EventBusService,
  ) {}

  async execute(cmd: ModerateTransferListingCommand): Promise<{ status: string }> {
    const entity = await this.repo.findById(cmd.listingId);
    if (!entity) {
      throw new NotFoundException('Transfer listing', cmd.listingId);
    }

    if (cmd.action === 'approve') {
      entity.approve(cmd.moderationScore, cmd.notes);
    } else {
      entity.reject(cmd.moderationScore, cmd.notes);
    }

    await this.repo.update(entity);

    this.eventBus.publish(new TransferListingUpdatedEvent(cmd.listingId));

    return { status: entity.status };
  }
}
