/**
 * @aurora-catalyst-generated
 * @source cliter/o-auth/refresh-token.aurora.yaml
 */
import { OAuthRefreshToken } from '@api/graphql';
import {
  OAuthDeleteRefreshTokenByIdService,
  OAuthFindRefreshTokenByIdService,
} from '@app/o-auth/refresh-token';
import { OAuthRefreshTokenFieldSchema } from '@app/o-auth/refresh-token/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 OAuthDeleteRefreshTokenByIdHandler {
  constructor(
    private readonly eventEmitter: EventEmitter2,
    private readonly deleteByIdService: OAuthDeleteRefreshTokenByIdService,
    private readonly findByIdService: OAuthFindRefreshTokenByIdService,
  ) {}

  @EmitEvent('oAuth.refreshToken.deleted')
  @Format(OAuthRefreshTokenFieldSchema)
  async main(
    id: string,
    constraint?: QueryStatement,
    handlerMeta?: HandlerMeta,
  ): Promise<OAuthRefreshToken> {
    const refreshToken = await this.findByIdService.main(id, constraint, handlerMeta);

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

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

    return refreshToken;
  }
}
