/**
 * @aurora-catalyst-generated
 * @source cliter/o-auth/application-client.aurora.yaml
 */
import { OAuthApplicationClient, OAuthUpdateApplicationClientByIdInput } from '@api/graphql';
import {
  OAuthFindApplicationClientByIdService,
  OAuthUpdateApplicationClientByIdService,
} from '@app/o-auth/application-client';
import { OAuthApplicationClientFieldSchema } from '@app/o-auth/application-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 OAuthUpdateApplicationClientByIdHandler {
  constructor(
    private readonly eventEmitter: EventEmitter2,
    private readonly updateByIdService: OAuthUpdateApplicationClientByIdService,
    private readonly findByIdService: OAuthFindApplicationClientByIdService,
  ) {}

  @EmitEvent('oAuth.applicationClient.updated')
  @ApplySchema(OAuthApplicationClientFieldSchema)
  async main(
    payload: OAuthUpdateApplicationClientByIdInput,
    constraint?: QueryStatement,
    handlerMeta?: HandlerMeta,
  ): Promise<OAuthApplicationClient> {
    const applicationClient = await this.findByIdService.main(
      payload.applicationId,
      payload.clientId,
      constraint,
      handlerMeta,
    );

    if (!applicationClient) {
      throw new NotFoundException(
        `OAuthApplicationClient with applicationId: ${payload.applicationId}, clientId: ${payload.clientId}, not found`,
      );
    }

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

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

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