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 { DeleteIndustrialListingCommand } from './delete-industrial-listing.command';

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

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

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