/**
 * @aurora-catalyst-generated
 * @source cliter/o-auth/client.aurora.yaml
 */
import { OAuthClient, OAuthUpdateClientByIdInput } from '@api/graphql';
import { OAuthFindClientByIdService, OAuthUpdateClientByIdService } from '@app/o-auth/client';
import { OAuthClientFieldSchema } from '@app/o-auth/client/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 OAuthUpdateClientByIdHandler {
  constructor(
    private readonly eventEmitter: EventEmitter2,
    private readonly updateByIdService: OAuthUpdateClientByIdService,
    private readonly findByIdService: OAuthFindClientByIdService,
  ) {}

  @EmitEvent('oAuth.client.updated')
  @ApplySchema(OAuthClientFieldSchema)
  async main(
    payload: OAuthUpdateClientByIdInput,
    constraint?: QueryStatement,
    handlerMeta?: HandlerMeta,
  ): Promise<OAuthClient> {
    const client = await this.findByIdService.main(payload.id, constraint, handlerMeta);

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

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

    if ('scopeOptions' in dataToUpdate) {
      dataToUpdate['scopeOptions'] = payload.scopeOptions;
    }

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

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