/**
 * @aurora-catalyst-generated
 * @source cliter/o-auth/application.aurora.yaml
 */
import { OAuthApplication, OAuthUpdateApplicationByIdInput } from '@api/graphql';
import {
  OAuthFindApplicationByIdService,
  OAuthUpdateApplicationByIdService,
} from '@app/o-auth/application';
import { OAuthApplicationFieldSchema } from '@app/o-auth/application/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 OAuthUpdateApplicationByIdHandler {
  constructor(
    private readonly eventEmitter: EventEmitter2,
    private readonly updateByIdService: OAuthUpdateApplicationByIdService,
    private readonly findByIdService: OAuthFindApplicationByIdService,
  ) {}

  @EmitEvent('oAuth.application.updated')
  @ApplySchema(OAuthApplicationFieldSchema)
  async main(
    payload: OAuthUpdateApplicationByIdInput,
    constraint?: QueryStatement,
    handlerMeta?: HandlerMeta,
  ): Promise<OAuthApplication> {
    const application = await this.findByIdService.main(payload.id, constraint, handlerMeta);

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

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

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

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