/**
 * @aurora-catalyst-generated
 * @source cliter/iam/user.aurora.yaml
 */
import { IamUser } from '@api/graphql';
import { IamDeleteUserByIdService, IamFindUserByIdService } from '@app/iam/user';
import { IamUserFieldSchema } from '@app/iam/user/domain';
import { EmitEvent, Format, HandlerMeta } from '@aurorajs.dev/core-back';
import { QueryStatement } from '@aurorajs.dev/core-common';
import { Injectable, NotFoundException } from '@nestjs/common';
import { EventEmitter2 } from '@nestjs/event-emitter';

@Injectable()
export class IamDeleteUserByIdHandler {
  constructor(
    private readonly eventEmitter: EventEmitter2,
    private readonly deleteByIdService: IamDeleteUserByIdService,
    private readonly findByIdService: IamFindUserByIdService,
  ) {}

  @EmitEvent('iam.user.deleted')
  @Format(IamUserFieldSchema)
  async main(id: string, constraint?: QueryStatement, handlerMeta?: HandlerMeta): Promise<IamUser> {
    const user = await this.findByIdService.main(id, constraint, handlerMeta);

    if (!user) {
      throw new NotFoundException(`IamUser with id: ${id}, not found`);
    }

    await this.deleteByIdService.main(id, constraint, handlerMeta);

    return user;
  }
}
