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

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

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

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

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

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