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

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

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

    if (entity.sellerId !== cmd.sellerId) {
      throw new ForbiddenException('You can only delete your own listings');
    }

    entity.updateDetails({ status: 'EXPIRED' });
    await this.repo.update(entity);

    this.eventBus.publish(
      new TransferListingDeletedEvent(cmd.id, cmd.sellerId),
    );

    return { id: cmd.id };
  }
}
