/**
 * @aurora-catalyst-generated
 * @source cliter/iam/user.aurora.yaml
 */
import { IamUpdateUserByIdInput, IamUser } from '@api/graphql';
import { IamFindUserByIdService, IamUpdateUserByIdService } from '@app/iam/user';
import { IamUserFieldSchema } from '@app/iam/user/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 IamUpdateUserByIdHandler {
  constructor(
    private readonly eventEmitter: EventEmitter2,
    private readonly updateByIdService: IamUpdateUserByIdService,
    private readonly findByIdService: IamFindUserByIdService,
  ) {}

  @EmitEvent('iam.user.updated')
  @ApplySchema(IamUserFieldSchema)
  async main(
    payload: IamUpdateUserByIdInput,
    constraint?: QueryStatement,
    handlerMeta?: HandlerMeta,
  ): Promise<IamUser> {
    const user = await this.findByIdService.main(payload.id, constraint, handlerMeta);

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

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

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

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