/**
 * @aurora-catalyst-generated
 * @source cliter/iam/tenant.aurora.yaml
 */
import { IamTenant, IamUpdateTenantByIdInput } from '@api/graphql';
import { IamFindTenantByIdService, IamUpdateTenantByIdService } from '@app/iam/tenant';
import { IamTenantFieldSchema } from '@app/iam/tenant/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 IamUpdateTenantByIdHandler {
  constructor(
    private readonly eventEmitter: EventEmitter2,
    private readonly updateByIdService: IamUpdateTenantByIdService,
    private readonly findByIdService: IamFindTenantByIdService,
  ) {}

  @EmitEvent('iam.tenant.updated')
  @ApplySchema(IamTenantFieldSchema)
  async main(
    payload: IamUpdateTenantByIdInput,
    constraint?: QueryStatement,
    handlerMeta?: HandlerMeta,
  ): Promise<IamTenant> {
    const tenant = await this.findByIdService.main(payload.id, constraint, handlerMeta);

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

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

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

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