/**
 * @aurora-catalyst-generated
 * @source cliter/o-auth/scope.aurora.yaml
 */
import { OAuthScope, OAuthUpdateScopeByIdInput } from '@api/graphql';
import { OAuthFindScopeByIdService, OAuthUpdateScopeByIdService } from '@app/o-auth/scope';
import { OAuthScopeFieldSchema } from '@app/o-auth/scope/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 OAuthUpdateScopeByIdHandler {
  constructor(
    private readonly eventEmitter: EventEmitter2,
    private readonly updateByIdService: OAuthUpdateScopeByIdService,
    private readonly findByIdService: OAuthFindScopeByIdService,
  ) {}

  @EmitEvent('oAuth.scope.updated')
  @ApplySchema(OAuthScopeFieldSchema)
  async main(
    payload: OAuthUpdateScopeByIdInput,
    constraint?: QueryStatement,
    handlerMeta?: HandlerMeta,
  ): Promise<OAuthScope> {
    const scope = await this.findByIdService.main(payload.id, constraint, handlerMeta);

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

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

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

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