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

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

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

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

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

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