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

export interface ReferralChainInfo {
  accountSequence: string;
  directReferrer: {
    accountSequence: string;
    hasPlanted: boolean;
  } | null;
}

/**
 * referral-service /api/v1/referral/chain/:accountSequence 的实际返回格式
 */
interface ReferralChainApiResponse {
  ancestors: Array<{
    userId: string;
    accountSequence: string;
    hasPlanted: boolean;
  }>;
}

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

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

  /**
   * 获取直接推荐人信息
   *
   * [2026-03-01] 修复：
   * 1. URL 路径修正：/api/v1/referral/chain/:accountSequence（之前错误地用了 /referrals/:accountSequence/chain）
   * 2. 返回格式修正：referral-service 返回 { ancestors: [{userId, accountSequence, hasPlanted}] }，
   *    之前错误地期望 { directReferrer: {accountSequence, hasPlanted} }
   * 3. ancestors[0] 即为直推人（直接推荐人）
   */
  async getReferralChain(accountSequence: string): Promise<ReferralChainInfo> {
    try {
      const response = await firstValueFrom(
        this.httpService.get<ReferralChainApiResponse>(
          `${this.baseUrl}/api/v1/referral/chain/${accountSequence}`,
        ),
      );

      const ancestors = response.data.ancestors || [];
      if (ancestors.length === 0) {
        this.logger.log(
          `No referrer found for ${accountSequence} (empty ancestors)`,
        );
        return { accountSequence, directReferrer: null };
      }

      // ancestors[0] 为直推人
      const directReferrer = ancestors[0];
      this.logger.log(
        `Referrer for ${accountSequence}: ${directReferrer.accountSequence} (hasPlanted=${directReferrer.hasPlanted})`,
      );

      return {
        accountSequence,
        directReferrer: {
          accountSequence: directReferrer.accountSequence,
          hasPlanted: directReferrer.hasPlanted ?? false,
        },
      };
    } catch (error) {
      if (error?.response?.status === 404) {
        this.logger.warn(
          `No referral chain found for ${accountSequence}, proceeding without referrer`,
        );
        return { accountSequence, directReferrer: null };
      }
      this.logger.error(
        `Failed to get referral chain for ${accountSequence}`,
        error,
      );
      throw error;
    }
  }
}
