import { Inject, InternalServerErrorException } from '@nestjs/common';
import { QueryHandler, type IQueryHandler } from '@nestjs/cqrs';
import { DomainException, LoggerService } from '@modules/shared';
import { ADMIN_QUERY_REPOSITORY, type IAdminQueryRepository, type KycQueueResult } from '../../../domain/repositories/admin-query.repository';
import { GetKycQueueQuery } from './get-kyc-queue.query';

@QueryHandler(GetKycQueueQuery)
export class GetKycQueueHandler implements IQueryHandler<GetKycQueueQuery> {
  constructor(
    @Inject(ADMIN_QUERY_REPOSITORY) private readonly adminQueryRepo: IAdminQueryRepository,
    private readonly logger: LoggerService,
  ) {}

  async execute(query: GetKycQueueQuery): Promise<KycQueueResult> {
    try {
      return await this.adminQueryRepo.getKycQueue(query.page, query.limit);
    } catch (error) {
      if (error instanceof DomainException) throw error;
      this.logger.error(
        `Failed to get KYC queue: ${error instanceof Error ? error.message : String(error)}`,
        error instanceof Error ? error.stack : undefined,
        'GetKycQueueHandler',
      );
      throw new InternalServerErrorException('Lỗi khi lấy danh sách KYC');
    }
  }
}
