/**
 * @aurora-catalyst-generated
 * @source cliter/iam/bounded-context.aurora.yaml
 */
import { IamBoundedContext, IamUpdateBoundedContextByIdInput } from '@api/graphql';
import {
  IamFindBoundedContextByIdService,
  IamUpdateBoundedContextByIdService,
} from '@app/iam/bounded-context';
import { IamBoundedContextFieldSchema } from '@app/iam/bounded-context/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 IamUpdateBoundedContextByIdHandler {
  constructor(
    private readonly eventEmitter: EventEmitter2,
    private readonly updateByIdService: IamUpdateBoundedContextByIdService,
    private readonly findByIdService: IamFindBoundedContextByIdService,
  ) {}

  @EmitEvent('iam.boundedContext.updated')
  @ApplySchema(IamBoundedContextFieldSchema)
  async main(
    payload: IamUpdateBoundedContextByIdInput,
    constraint?: QueryStatement,
    handlerMeta?: HandlerMeta,
  ): Promise<IamBoundedContext> {
    const boundedContext = await this.findByIdService.main(payload.id, constraint, handlerMeta);

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

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

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

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