/**
 * Blockchain Client Service
 *
 * mpc-service 调用 blockchain-service 派生钱包地址
 */

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

export interface DeriveAddressParams {
  userId: string;
  accountSequence: string;  // 账户序列号，格式: D + YYMMDD + 5位序号，如 D2512110008
  publicKey: string;
}

export interface DerivedAddress {
  chainType: string;
  address: string;
}

export interface DeriveAddressResult {
  userId: string;
  publicKey: string;
  addresses: DerivedAddress[];
}

@Injectable()
export class BlockchainClientService {
  private readonly logger = new Logger(BlockchainClientService.name);
  private readonly blockchainServiceUrl: string;

  constructor(
    private readonly httpService: HttpService,
    private readonly configService: ConfigService,
  ) {
    this.blockchainServiceUrl = this.configService.get<string>(
      'BLOCKCHAIN_SERVICE_URL',
      'http://blockchain-service:3000',
    );
    this.logger.log(`[INIT] BlockchainClientService initialized`);
    this.logger.log(`[INIT] URL: ${this.blockchainServiceUrl}`);
  }

  /**
   * 从公钥派生多链地址 (BSC, KAVA, DST)
   */
  async deriveAddresses(params: DeriveAddressParams): Promise<DeriveAddressResult> {
    this.logger.log(`Deriving addresses: userId=${params.userId}, publicKey=${params.publicKey.substring(0, 20)}...`);

    try {
      const response = await firstValueFrom(
        this.httpService.post<DeriveAddressResult>(
          `${this.blockchainServiceUrl}/api/v1/internal/derive-address`,
          {
            userId: params.userId,
            accountSequence: params.accountSequence,
            publicKey: params.publicKey,
          },
          {
            headers: {
              'Content-Type': 'application/json',
            },
            timeout: 30000,
          },
        ),
      );

      this.logger.log(`Addresses derived successfully: userId=${params.userId}, count=${response.data.addresses.length}`);
      for (const addr of response.data.addresses) {
        this.logger.log(`  ${addr.chainType}: ${addr.address}`);
      }

      return response.data;
    } catch (error) {
      this.logger.error(`Failed to derive addresses: userId=${params.userId}`, error);
      throw error;
    }
  }

  /**
   * 获取用户已有的地址
   */
  async getUserAddresses(userId: string): Promise<DerivedAddress[]> {
    this.logger.log(`Getting user addresses: userId=${userId}`);

    try {
      const response = await firstValueFrom(
        this.httpService.get<{ userId: string; addresses: DerivedAddress[] }>(
          `${this.blockchainServiceUrl}/api/v1/internal/user/${userId}/addresses`,
          {
            timeout: 30000,
          },
        ),
      );

      return response.data.addresses;
    } catch (error) {
      this.logger.error(`Failed to get user addresses: userId=${userId}`, error);
      throw error;
    }
  }
}
