/**
 * @aurora-catalyst-generated
 * @source cliter/o-auth/authorization-code.aurora.yaml
 */
import { OAuthAuthorizationCode, OAuthUpdateAuthorizationCodeByIdInput } from '@api/graphql';
import {
  OAuthFindAuthorizationCodeByIdService,
  OAuthUpdateAuthorizationCodeByIdService,
} from '@app/o-auth/authorization-code';
import { OAuthAuthorizationCodeFieldSchema } from '@app/o-auth/authorization-code/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 OAuthUpdateAuthorizationCodeByIdHandler {
  constructor(
    private readonly eventEmitter: EventEmitter2,
    private readonly updateByIdService: OAuthUpdateAuthorizationCodeByIdService,
    private readonly findByIdService: OAuthFindAuthorizationCodeByIdService,
  ) {}

  @EmitEvent('oAuth.authorizationCode.updated')
  @ApplySchema(OAuthAuthorizationCodeFieldSchema)
  async main(
    payload: OAuthUpdateAuthorizationCodeByIdInput,
    constraint?: QueryStatement,
    handlerMeta?: HandlerMeta,
  ): Promise<OAuthAuthorizationCode> {
    const authorizationCode = await this.findByIdService.main(payload.id, constraint, handlerMeta);

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

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

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

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