import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import axios, { AxiosInstance } from 'axios';
import {
  ITeamStatisticsRepository,
  TeamStatistics,
} from '../../domain/services/assessment-calculator.service';

/**
 * 团队统计数据接口（来自 referral-service）
 */
interface ReferralTeamStatsResponse {
  userId: string;
  accountSequence: string;
  totalTeamPlantingCount: number;
  selfPlantingCount: number;
  provinceCityDistribution: Record<string, Record<string, number>> | null;
}

/**
 * 推荐链数据接口
 */
interface ReferralChainResponse {
  accountSequence: string;
  userId: string | null;
  ancestorPath: string[];
  referrerId: string | null;
}

/**
 * 团队成员数据接口
 */
interface TeamMembersResponse {
  accountSequence: string;
  teamMembers: string[];
}

/**
 * 用户资料统计接口
 */
export interface UserProfileStatsResponse {
  accountSequence: string;
  directReferralCount: number;
  umbrellaUserCount: number;
  personalPlantingCount: number;
  teamPlantingCount: number;
}

/**
 * 适配器类：将 referral-service 返回的数据转换为 authorization-service 需要的格式
 */
class TeamStatisticsAdapter implements TeamStatistics {
  constructor(
    public readonly userId: string,
    public readonly accountSequence: string,
    public readonly totalTeamPlantingCount: number,
    public readonly selfPlantingCount: number,
    private readonly provinceCityDistribution: Record<string, Record<string, number>> | null,
  ) {}

  /** 下级团队认种数（不包括自己）
   * 注意：referral-service 返回的 totalTeamPlantingCount 已经是"下级团队认种数"，
   * 不包括自己的认种数，所以直接返回即可，不需要再减 selfPlantingCount
   */
  get subordinateTeamPlantingCount(): number {
    return this.totalTeamPlantingCount;
  }

  getProvinceTeamCount(provinceCode: string): number {
    if (!this.provinceCityDistribution || !this.provinceCityDistribution[provinceCode]) {
      return 0;
    }
    // 计算该省所有城市的总和
    const provinceCities = this.provinceCityDistribution[provinceCode];
    return Object.values(provinceCities).reduce((sum, count) => sum + count, 0);
  }

  getCityTeamCount(cityCode: string): number {
    if (!this.provinceCityDistribution) {
      return 0;
    }
    // 遍历所有省份找到该城市
    for (const provinceCode of Object.keys(this.provinceCityDistribution)) {
      const provinceCities = this.provinceCityDistribution[provinceCode];
      if (provinceCities && cityCode in provinceCities) {
        return provinceCities[cityCode];
      }
    }
    return 0;
  }
}

/**
 * Referral Service HTTP 客户端
 * 用于从 referral-service 获取团队统计数据
 */
@Injectable()
export class ReferralServiceClient implements ITeamStatisticsRepository, OnModuleInit {
  private readonly logger = new Logger(ReferralServiceClient.name);
  private httpClient: AxiosInstance;
  private readonly baseUrl: string;
  private readonly enabled: boolean;

  constructor(private readonly configService: ConfigService) {
    this.baseUrl = this.configService.get<string>('REFERRAL_SERVICE_URL') || 'http://referral-service:3004';
    this.enabled = this.configService.get<boolean>('REFERRAL_SERVICE_ENABLED') !== false;
  }

  onModuleInit() {
    this.httpClient = axios.create({
      baseURL: this.baseUrl,
      timeout: 10000,
      headers: {
        'Content-Type': 'application/json',
      },
    });

    this.logger.log(`[INIT] ReferralServiceClient initialized: ${this.baseUrl}, enabled: ${this.enabled}`);
  }

  /**
   * 根据 userId 查询团队统计
   */
  async findByUserId(userId: string): Promise<TeamStatistics | null> {
    if (!this.enabled) {
      this.logger.debug('[DISABLED] Referral service integration is disabled');
      return this.createEmptyStats(userId, '0');
    }

    try {
      this.logger.debug(`[HTTP] GET /internal/team-statistics/user/${userId}`);

      const response = await this.httpClient.get<ReferralTeamStatsResponse | null>(
        `/api/v1/internal/team-statistics/user/${userId}`,
      );

      if (!response.data) {
        this.logger.debug(`[HTTP] No stats found for userId: ${userId}`);
        return this.createEmptyStats(userId, '0');
      }

      const data = response.data;
      this.logger.debug(`[HTTP] Got stats for userId ${userId}: totalTeamPlantingCount=${data.totalTeamPlantingCount}`);

      return new TeamStatisticsAdapter(
        data.userId,
        data.accountSequence || '0',
        data.totalTeamPlantingCount,
        data.selfPlantingCount || 0,
        data.provinceCityDistribution,
      );
    } catch (error) {
      this.logger.error(`[HTTP] Failed to get stats for userId ${userId}:`, error);
      // 返回空数据而不是抛出错误，避免影响主流程
      return this.createEmptyStats(userId, '0');
    }
  }

  /**
   * 根据 accountSequence 查询团队统计
   */
  async findByAccountSequence(accountSequence: string): Promise<TeamStatistics | null> {
    if (!this.enabled) {
      this.logger.debug('[DISABLED] Referral service integration is disabled');
      return this.createEmptyStats('', accountSequence);
    }

    try {
      this.logger.debug(`[HTTP] GET /internal/team-statistics/account/${accountSequence}`);

      const response = await this.httpClient.get<ReferralTeamStatsResponse | null>(
        `/api/v1/internal/team-statistics/account/${accountSequence}`,
      );

      if (!response.data) {
        this.logger.debug(`[HTTP] No stats found for accountSequence: ${accountSequence}`);
        return this.createEmptyStats('', accountSequence);
      }

      const data = response.data;
      this.logger.debug(`[HTTP] Got stats for accountSequence ${accountSequence}: totalTeamPlantingCount=${data.totalTeamPlantingCount}, selfPlantingCount=${data.selfPlantingCount}`);

      return new TeamStatisticsAdapter(
        data.userId,
        data.accountSequence || accountSequence,
        data.totalTeamPlantingCount,
        data.selfPlantingCount || 0,
        data.provinceCityDistribution,
      );
    } catch (error) {
      this.logger.error(`[HTTP] Failed to get stats for accountSequence ${accountSequence}:`, error);
      // 返回空数据而不是抛出错误，避免影响主流程
      return this.createEmptyStats('', accountSequence);
    }
  }

  /**
   * 创建空的统计数据
   */
  private createEmptyStats(userId: string, accountSequence: string): TeamStatistics {
    return new TeamStatisticsAdapter(userId, accountSequence, 0, 0, null);
  }

  /**
   * 获取用户的祖先链（推荐链）
   * 返回从直接推荐人到根节点的 accountSequence 列表
   */
  async getReferralChain(accountSequence: string): Promise<string[]> {
    if (!this.enabled) {
      this.logger.debug('[DISABLED] Referral service integration is disabled');
      return [];
    }

    try {
      this.logger.debug(`[HTTP] GET /internal/referral-chain/${accountSequence}`);

      const response = await this.httpClient.get<ReferralChainResponse>(
        `/api/v1/internal/referral-chain/${accountSequence}`,
      );

      if (!response.data || !response.data.ancestorPath) {
        return [];
      }

      // ancestorPath 存储的是 accountSequence string
      return response.data.ancestorPath;
    } catch (error) {
      this.logger.error(`[HTTP] Failed to get referral chain for accountSequence ${accountSequence}:`, error);
      return [];
    }
  }

  /**
   * 获取用户的团队成员 accountSequence 列表
   */
  async getTeamMembers(accountSequence: string): Promise<string[]> {
    if (!this.enabled) {
      this.logger.debug('[DISABLED] Referral service integration is disabled');
      return [];
    }

    try {
      this.logger.debug(`[HTTP] GET /internal/referral-chain/${accountSequence}/team-members`);

      const response = await this.httpClient.get<TeamMembersResponse>(
        `/api/v1/internal/referral-chain/${accountSequence}/team-members`,
      );

      if (!response.data || !response.data.teamMembers) {
        return [];
      }

      return response.data.teamMembers;
    } catch (error) {
      this.logger.error(`[HTTP] Failed to get team members for accountSequence ${accountSequence}:`, error);
      return [];
    }
  }

  /**
   * 获取用户资料统计（用于用户详情页）
   */
  async getUserProfileStats(accountSequence: string): Promise<UserProfileStatsResponse> {
    const emptyStats: UserProfileStatsResponse = {
      accountSequence,
      directReferralCount: 0,
      umbrellaUserCount: 0,
      personalPlantingCount: 0,
      teamPlantingCount: 0,
    };

    if (!this.enabled) {
      this.logger.debug('[DISABLED] Referral service integration is disabled');
      return emptyStats;
    }

    try {
      this.logger.debug(`[HTTP] GET /internal/referral-chain/${accountSequence}/profile-stats`);

      const response = await this.httpClient.get<UserProfileStatsResponse>(
        `/api/v1/internal/referral-chain/${accountSequence}/profile-stats`,
      );

      if (!response.data) {
        return emptyStats;
      }

      return response.data;
    } catch (error) {
      this.logger.error(`[HTTP] Failed to get profile stats for accountSequence ${accountSequence}:`, error);
      return emptyStats;
    }
  }
}
