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

export interface UserInfo {
  accountSequence: string;
  kavaAddress?: string;
  phone?: string;
  nickname?: string;
}

/**
 * Auth 服务客户端（通过 auth-service 内部 API 获取用户信息）
 * 用于获取用户信息，包括 Kava 地址
 */
@Injectable()
export class IdentityClient {
  private readonly logger = new Logger(IdentityClient.name);
  private readonly baseUrl: string;

  constructor(
    private readonly httpService: HttpService,
    private readonly configService: ConfigService,
  ) {
    this.baseUrl = this.configService.get<string>(
      'AUTH_SERVICE_URL',
      'http://localhost:3024',
    );
    this.logger.log(`[INIT] IdentityClient initialized with auth-service URL: ${this.baseUrl}`);
  }

  /**
   * 获取用户的 Kava 地址（调用 auth-service 内部 API）
   * @param accountSequence 用户账户序列号
   */
  async getUserKavaAddress(accountSequence: string): Promise<string | null> {
    try {
      // auth-service TransformInterceptor 会包装响应为 { success, data: { kavaAddress }, timestamp }
      const response: AxiosResponse<{ data?: { kavaAddress?: string }; kavaAddress?: string }> =
        await firstValueFrom(
          this.httpService.get(
            `${this.baseUrl}/api/v2/internal/users/${accountSequence}/kava-address`,
          ),
        );

      const body = response.data;
      return body?.data?.kavaAddress || body?.kavaAddress || null;
    } catch (error: any) {
      this.logger.error(`Failed to get Kava address for ${accountSequence}: ${error.message}`);
      return null;
    }
  }

  /**
   * 获取用户信息
   * @param accountSequence 用户账户序列号
   */
  async getUserInfo(accountSequence: string): Promise<UserInfo | null> {
    try {
      // auth-service TransformInterceptor 会包装响应为 { success, data: {...}, timestamp }
      const response: AxiosResponse<{ data?: UserInfo } & UserInfo> = await firstValueFrom(
        this.httpService.get(
          `${this.baseUrl}/api/v2/internal/users/${accountSequence}`,
        ),
      );

      const body = response.data;
      return body?.data || body || null;
    } catch (error: any) {
      this.logger.error(`Failed to get user info for ${accountSequence}: ${error.message}`);
      return null;
    }
  }
}
