/**
 * @aurora-catalyst-generated
 * @source cliter/iam/permission-role.aurora.yaml
 */
import { IamPermissionRole } from '@api/graphql';
import {
  IamDeletePermissionRoleByIdService,
  IamFindPermissionRoleByIdService,
} from '@app/iam/permission-role';
import { IamPermissionRoleFieldSchema } from '@app/iam/permission-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 IamDeletePermissionRoleByIdHandler {
  constructor(
    private readonly eventEmitter: EventEmitter2,
    private readonly deleteByIdService: IamDeletePermissionRoleByIdService,
    private readonly findByIdService: IamFindPermissionRoleByIdService,
  ) {}

  @EmitEvent('iam.permissionRole.deleted')
  @Format(IamPermissionRoleFieldSchema)
  async main(
    permissionId: string,
    roleId: string,
    constraint?: QueryStatement,
    handlerMeta?: HandlerMeta,
  ): Promise<IamPermissionRole> {
    const permissionRole = await this.findByIdService.main(
      permissionId,
      roleId,
      constraint,
      handlerMeta,
    );

    if (!permissionRole) {
      throw new NotFoundException(
        `IamPermissionRole with permissionId: ${permissionId}, roleId: ${roleId}, not found`,
      );
    }

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

    return permissionRole;
  }
}
