import { Inject } from '@nestjs/common';
import { type ICommandHandler, CommandHandler } from '@nestjs/cqrs';
import { NotFoundException } from '@modules/shared';
import {
  INDUSTRIAL_LISTING_REPOSITORY,
  type IIndustrialListingRepository,
} from '../../../domain/repositories/industrial-listing.repository';
import { TypesenseIndustrialService } from '../../../infrastructure/services/typesense-industrial.service';
import { UpdateIndustrialListingCommand } from './update-industrial-listing.command';

@CommandHandler(UpdateIndustrialListingCommand)
export class UpdateIndustrialListingHandler implements ICommandHandler<UpdateIndustrialListingCommand> {
  constructor(
    @Inject(INDUSTRIAL_LISTING_REPOSITORY)
    private readonly repo: IIndustrialListingRepository,
    private readonly typesense: TypesenseIndustrialService,
  ) {}

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

    entity.updateDetails({
      propertyType: cmd.propertyType,
      leaseType: cmd.leaseType,
      status: cmd.status,
      title: cmd.title,
      description: cmd.description,
      areaM2: cmd.areaM2,
      ceilingHeightM: cmd.ceilingHeightM,
      floorLoadTonM2: cmd.floorLoadTonM2,
      columnSpacingM: cmd.columnSpacingM,
      dockCount: cmd.dockCount,
      craneCapacityTon: cmd.craneCapacityTon,
      hasMezzanine: cmd.hasMezzanine,
      hasOfficeArea: cmd.hasOfficeArea,
      officeAreaM2: cmd.officeAreaM2,
      priceUsdM2: cmd.priceUsdM2,
      pricingUnit: cmd.pricingUnit,
      totalLeasePrice: cmd.totalLeasePrice,
      managementFee: cmd.managementFee,
      depositMonths: cmd.depositMonths,
      minLeaseYears: cmd.minLeaseYears,
      maxLeaseYears: cmd.maxLeaseYears,
      leaseExpiry: cmd.leaseExpiry,
      availableFrom: cmd.availableFrom,
      powerCapacityKva: cmd.powerCapacityKva,
      waterSupplyM3Day: cmd.waterSupplyM3Day,
      media: cmd.media,
    });

    await this.repo.update(entity);
    await this.typesense.indexListing(entity.id).catch(() => {});
  }
}
