/**
 * @aurora-catalyst-generated
 * @source cliter/iam/tenant-account.aurora.yaml
 */
import { IamTenantAccount, IamUpdateTenantAccountByIdInput } from '@api/graphql';
import {
  IamFindTenantAccountByIdService,
  IamUpdateTenantAccountByIdService,
} from '@app/iam/tenant-account';
import { IamTenantAccountFieldSchema } from '@app/iam/tenant-account/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 IamUpdateTenantAccountByIdHandler {
  constructor(
    private readonly eventEmitter: EventEmitter2,
    private readonly updateByIdService: IamUpdateTenantAccountByIdService,
    private readonly findByIdService: IamFindTenantAccountByIdService,
  ) {}

  @EmitEvent('iam.tenantAccount.updated')
  @ApplySchema(IamTenantAccountFieldSchema)
  async main(
    payload: IamUpdateTenantAccountByIdInput,
    constraint?: QueryStatement,
    handlerMeta?: HandlerMeta,
  ): Promise<IamTenantAccount> {
    const tenantAccount = await this.findByIdService.main(
      payload.tenantId,
      payload.accountId,
      constraint,
      handlerMeta,
    );

    if (!tenantAccount) {
      throw new NotFoundException(
        `IamTenantAccount with tenantId: ${payload.tenantId}, accountId: ${payload.accountId}, not found`,
      );
    }

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

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

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