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

/**
 * Planting Service 客户端
 * 查询认种订单和持仓信息
 */
@Injectable()
export class PlantingServiceClient {
  private readonly logger = new Logger(PlantingServiceClient.name);
  private readonly baseUrl: string;

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

  /**
   * 查询认种订单详情（包含可转让信息）
   */
  async getPlantingOrder(orderNo: string): Promise<{
    id: number;
    orderNo: string;
    userId: number;
    accountSequence: string;
    treeCount: number;
    status: string;
    selectedProvince: string;
    selectedCity: string;
    transferLockedCount: number;
    transferredCount: number;
    availableForTransfer: number;
    miningEnabledAt: string;
    createdAt: string;
  } | null> {
    const url = `${this.baseUrl}/api/v1/internal/planting-orders/${orderNo}`;
    try {
      const { data } = await firstValueFrom(this.httpService.get(url));
      return data;
    } catch (error: any) {
      if (error?.response?.status === 404) return null;
      throw error;
    }
  }

  /**
   * 查询用户持仓
   */
  async getUserPosition(userId: string): Promise<{
    userId: number;
    totalTreeCount: number;
    effectiveTreeCount: number;
  } | null> {
    const url = `${this.baseUrl}/api/v1/internal/planting-positions/${userId}`;
    try {
      const { data } = await firstValueFrom(this.httpService.get(url));
      return data;
    } catch (error: any) {
      if (error?.response?.status === 404) return null;
      throw error;
    }
  }

  /**
   * 查询树的原始算力值
   */
  async getContributionPerTree(orderNo: string): Promise<{
    contributionPerTree: string;
    adoptionDate: string;
    expireDate: string;
  }> {
    const url = `${this.baseUrl}/api/v1/internal/planting-orders/${orderNo}/contribution`;
    const { data } = await firstValueFrom(this.httpService.get(url));
    return data;
  }
}
