/**
 * @aurora-catalyst-generated
 * @source cliter/iam/role-account.aurora.yaml
 */
import { IamRoleAccount, IamUpdateRoleAccountByIdInput } from '@api/graphql';
import {
  IamFindRoleAccountByIdService,
  IamUpdateRoleAccountByIdService,
} from '@app/iam/role-account';
import { IamRoleAccountFieldSchema } from '@app/iam/role-account/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 IamUpdateRoleAccountByIdHandler {
  constructor(
    private readonly eventEmitter: EventEmitter2,
    private readonly updateByIdService: IamUpdateRoleAccountByIdService,
    private readonly findByIdService: IamFindRoleAccountByIdService,
  ) {}

  @EmitEvent('iam.roleAccount.updated')
  @ApplySchema(IamRoleAccountFieldSchema)
  async main(
    payload: IamUpdateRoleAccountByIdInput,
    constraint?: QueryStatement,
    handlerMeta?: HandlerMeta,
  ): Promise<IamRoleAccount> {
    const roleAccount = await this.findByIdService.main(
      payload.roleId,
      payload.accountId,
      constraint,
      handlerMeta,
    );

    if (!roleAccount) {
      throw new NotFoundException(
        `IamRoleAccount with roleId: ${payload.roleId}, accountId: ${payload.accountId}, not found`,
      );
    }

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

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

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