import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { HttpService } from '@nestjs/axios';
import { firstValueFrom } from 'rxjs';
import { ReferralContext } from '../../domain/services/fund-allocation.service';

export interface ReferralInfo {
  userId: string;
  referralChain: string[];
  nearestProvinceAuth: string | null;
  nearestCityAuth: string | null;
  nearestCommunity: string | null;
}

@Injectable()
export class ReferralServiceClient {
  private readonly logger = new Logger(ReferralServiceClient.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';
  }

  /**
   * 获取用户的推荐链和权限上级信息
   */
  async getReferralContext(
    accountSequence: string,
    provinceCode: string,
    cityCode: string,
  ): Promise<ReferralContext> {
    try {
      const response = await firstValueFrom(
        this.httpService.get<ReferralInfo>(
          `${this.baseUrl}/api/v1/referrals/${accountSequence}/context`,
          {
            params: { provinceCode, cityCode },
          },
        ),
      );

      return {
        referralChain: response.data.referralChain,
        nearestProvinceAuth: response.data.nearestProvinceAuth,
        nearestCityAuth: response.data.nearestCityAuth,
        nearestCommunity: response.data.nearestCommunity,
      };
    } catch (error) {
      this.logger.error(
        `Failed to get referral context for accountSequence ${accountSequence}`,
        error,
      );
      // 在开发环境返回默认空数据
      if (this.configService.get('NODE_ENV') === 'development') {
        this.logger.warn(
          'Development mode: returning empty referral context',
        );
        return {
          referralChain: [],
          nearestProvinceAuth: null,
          nearestCityAuth: null,
          nearestCommunity: null,
        };
      }
      throw error;
    }
  }
}
