/**
 * @aurora-catalyst-generated
 * @source cliter/iam/tenant.aurora.yaml
 */
import { IamTenant } from '@api/graphql';
import { IamDeleteTenantByIdService, IamFindTenantByIdService } from '@app/iam/tenant';
import { IamTenantFieldSchema } from '@app/iam/tenant/domain';
import { EmitEvent, Format, HandlerMeta } from '@aurorajs.dev/core-back';
import { QueryStatement } from '@aurorajs.dev/core-common';
import { Injectable, NotFoundException } from '@nestjs/common';
import { EventEmitter2 } from '@nestjs/event-emitter';

@Injectable()
export class IamDeleteTenantByIdHandler {
  constructor(
    private readonly eventEmitter: EventEmitter2,
    private readonly deleteByIdService: IamDeleteTenantByIdService,
    private readonly findByIdService: IamFindTenantByIdService,
  ) {}

  @EmitEvent('iam.tenant.deleted')
  @Format(IamTenantFieldSchema)
  async main(
    id: string,
    constraint?: QueryStatement,
    handlerMeta?: HandlerMeta,
  ): Promise<IamTenant> {
    const tenant = await this.findByIdService.main(id, constraint, handlerMeta);

    if (!tenant) {
      throw new NotFoundException(`IamTenant with id: ${id}, not found`);
    }

    await this.deleteByIdService.main(id, constraint, handlerMeta);

    return tenant;
  }
}
