/**
 * @aurora-catalyst-generated
 * @source cliter/iam/role-account.aurora.yaml
 */
import { IamRoleAccount } from '@api/graphql';
import {
  IamDeleteRoleAccountByIdService,
  IamFindRoleAccountByIdService,
} from '@app/iam/role-account';
import { IamRoleAccountFieldSchema } from '@app/iam/role-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 IamDeleteRoleAccountByIdHandler {
  constructor(
    private readonly eventEmitter: EventEmitter2,
    private readonly deleteByIdService: IamDeleteRoleAccountByIdService,
    private readonly findByIdService: IamFindRoleAccountByIdService,
  ) {}

  @EmitEvent('iam.roleAccount.deleted')
  @Format(IamRoleAccountFieldSchema)
  async main(
    roleId: string,
    accountId: string,
    constraint?: QueryStatement,
    handlerMeta?: HandlerMeta,
  ): Promise<IamRoleAccount> {
    const roleAccount = await this.findByIdService.main(roleId, accountId, constraint, handlerMeta);

    if (!roleAccount) {
      throw new NotFoundException(
        `IamRoleAccount with roleId: ${roleId}, accountId: ${accountId}, not found`,
      );
    }

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

    return roleAccount;
  }
}
