/**
 * @aurora-catalyst-generated
 * @source cliter/iam/tag.aurora.yaml
 */
import { IamTag, IamUpdateTagByIdInput } from '@api/graphql';
import { IamFindTagByIdService, IamUpdateTagByIdService } from '@app/iam/tag';
import { IamTagFieldSchema } from '@app/iam/tag/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 IamUpdateTagByIdHandler {
  constructor(
    private readonly eventEmitter: EventEmitter2,
    private readonly updateByIdService: IamUpdateTagByIdService,
    private readonly findByIdService: IamFindTagByIdService,
  ) {}

  @EmitEvent('iam.tag.updated')
  @ApplySchema(IamTagFieldSchema)
  async main(
    payload: IamUpdateTagByIdInput,
    constraint?: QueryStatement,
    handlerMeta?: HandlerMeta,
  ): Promise<IamTag> {
    const tag = await this.findByIdService.main(payload.id, constraint, handlerMeta);

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

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

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

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