/**
 * @aurora-catalyst-generated
 * @source cliter/iam/tenant-account.aurora.yaml
 */
import { IamTenantAccount } from '@api/graphql';
import {
  IamDeleteTenantAccountByIdService,
  IamFindTenantAccountByIdService,
} from '@app/iam/tenant-account';
import { IamTenantAccountFieldSchema } from '@app/iam/tenant-account/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 IamDeleteTenantAccountByIdHandler {
  constructor(
    private readonly eventEmitter: EventEmitter2,
    private readonly deleteByIdService: IamDeleteTenantAccountByIdService,
    private readonly findByIdService: IamFindTenantAccountByIdService,
  ) {}

  @EmitEvent('iam.tenantAccount.deleted')
  @Format(IamTenantAccountFieldSchema)
  async main(
    tenantId: string,
    accountId: string,
    constraint?: QueryStatement,
    handlerMeta?: HandlerMeta,
  ): Promise<IamTenantAccount> {
    const tenantAccount = await this.findByIdService.main(
      tenantId,
      accountId,
      constraint,
      handlerMeta,
    );

    if (!tenantAccount) {
      throw new NotFoundException(
        `IamTenantAccount with tenantId: ${tenantId}, accountId: ${accountId}, not found`,
      );
    }

    await this.deleteByIdService.main(tenantId, accountId, constraint, handlerMeta);

    return tenantAccount;
  }
}
