import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { IReferralServiceClient } from '../../../domain/services/reward-calculation.service';

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

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

  async getReferralChain(accountSequence: string): Promise<{
    ancestors: Array<{ userId: bigint; accountSequence: string; hasPlanted: boolean }>;
  }> {
    try {
      this.logger.log(`Fetching referral chain for accountSequence: ${accountSequence}`);
      const response = await fetch(`${this.baseUrl}/api/v1/referral/chain/${accountSequence}`);

      if (!response.ok) {
        this.logger.warn(`Failed to get referral chain for accountSequence ${accountSequence}: ${response.status}`);
        return { ancestors: [] };
      }

      const data = await response.json();
      this.logger.log(`Referral chain response: ${JSON.stringify(data)}`);

      return {
        ancestors: (data.ancestors || []).map((a: any) => ({
          userId: BigInt(a.userId),
          accountSequence: a.accountSequence || a.userId,
          hasPlanted: a.hasPlanted ?? false,
        })),
      };
    } catch (error) {
      this.logger.error(`Error fetching referral chain for accountSequence ${accountSequence}:`, error);
      return { ancestors: [] };
    }
  }
}
