/**
 * @aurora-catalyst-generated
 * @source cliter/iam/permission.aurora.yaml
 */
import { IamPermission, IamUpdatePermissionByIdInput } from '@api/graphql';
import { IamFindPermissionByIdService, IamUpdatePermissionByIdService } from '@app/iam/permission';
import { IamPermissionFieldSchema } from '@app/iam/permission/domain';
import { ApplySchema, EmitEvent, HandlerMeta } from '@aurorajs.dev/core-back';
import { Obj, QueryStatement } from '@aurorajs.dev/core-common';
import { Injectable, NotFoundException } from '@nestjs/common';
import { EventEmitter2 } from '@nestjs/event-emitter';

@Injectable()
export class IamUpdatePermissionByIdHandler {
  constructor(
    private readonly eventEmitter: EventEmitter2,
    private readonly updateByIdService: IamUpdatePermissionByIdService,
    private readonly findByIdService: IamFindPermissionByIdService,
  ) {}

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

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

    const dataToUpdate = Obj.diff(payload, permission);

    await this.updateByIdService.main(
      {
        ...dataToUpdate,
        id: payload.id,
      },
      constraint,
      handlerMeta,
    );

    return await this.findByIdService.main(payload.id, constraint, handlerMeta);
  }
}
