import { Injectable, Logger } from '@nestjs/common';
import { HttpService } from '@nestjs/axios';
import { ConfigService } from '@nestjs/config';
import { firstValueFrom } from 'rxjs';

/**
 * Identity Service 客户端
 * 验证用户身份和实名认证状态
 */
@Injectable()
export class IdentityServiceClient {
  private readonly logger = new Logger(IdentityServiceClient.name);
  private readonly baseUrl: string;

  constructor(
    private readonly httpService: HttpService,
    private readonly configService: ConfigService,
  ) {
    this.baseUrl = this.configService.get<string>(
      'external.identityServiceUrl',
      'http://localhost:3000',
    );
  }

  /**
   * 检查用户是否已实名认证
   */
  async isKycVerified(userId: string): Promise<boolean> {
    const url = `${this.baseUrl}/api/v1/internal/users/${userId}/kyc-status`;
    try {
      const { data } = await firstValueFrom(this.httpService.get(url));
      return data.verified === true;
    } catch {
      return false;
    }
  }

  /**
   * 获取用户信息
   */
  async getUserInfo(userId: string): Promise<{
    userId: number;
    accountSequence: string;
    kycVerified: boolean;
  } | null> {
    const url = `${this.baseUrl}/api/v1/internal/users/${userId}`;
    try {
      const { data } = await firstValueFrom(this.httpService.get(url));
      return data;
    } catch (error: any) {
      if (error?.response?.status === 404) return null;
      throw error;
    }
  }
}
