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 { UpdateTransferListingCommand } from './update-transfer-listing.command';

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

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

    entity.updateDetails({
      title: cmd.title,
      description: cmd.description,
      status: cmd.status,
      askingPriceVND: cmd.askingPriceVND,
      isNegotiable: cmd.isNegotiable,
      areaM2: cmd.areaM2,
      monthlyRentVND: cmd.monthlyRentVND,
      depositMonths: cmd.depositMonths,
      remainingLeaseMo: cmd.remainingLeaseMo,
      businessType: cmd.businessType,
      footTraffic: cmd.footTraffic,
      contactPhone: cmd.contactPhone,
      contactName: cmd.contactName,
      media: cmd.media,
    });

    await this.repo.update(entity);

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

    return { id: cmd.id };
  }
}
