/**
 * @aurora-catalyst-generated
 * @source cliter/iam/permission.aurora.yaml
 */
import { IamPermission } from '@api/graphql';
import { IamDeletePermissionByIdService, IamFindPermissionByIdService } from '@app/iam/permission';
import { IamPermissionFieldSchema } from '@app/iam/permission/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 IamDeletePermissionByIdHandler {
  constructor(
    private readonly eventEmitter: EventEmitter2,
    private readonly deleteByIdService: IamDeletePermissionByIdService,
    private readonly findByIdService: IamFindPermissionByIdService,
  ) {}

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

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

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

    return permission;
  }
}
