/**
 * @aurora-catalyst-generated
 * @source cliter/iam/role.aurora.yaml
 */
import { IamRole } from '@api/graphql';
import { IamDeleteRoleByIdService, IamFindRoleByIdService } from '@app/iam/role';
import { IamRoleFieldSchema } from '@app/iam/role/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 IamDeleteRoleByIdHandler {
  constructor(
    private readonly eventEmitter: EventEmitter2,
    private readonly deleteByIdService: IamDeleteRoleByIdService,
    private readonly findByIdService: IamFindRoleByIdService,
  ) {}

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

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

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

    return role;
  }
}
