import { Injectable, Inject } from '@nestjs/common';
import {
  ISyncedDataRepository,
  SYNCED_DATA_REPOSITORY,
} from '../../domain/repositories/synced-data.repository.interface';

/**
 * 团队成员信息
 */
export interface TeamMemberDto {
  accountSequence: string;
  personalPlantingCount: number;
  teamPlantingCount: number;
  directReferralCount: number;
}

/**
 * 直推列表响应
 */
export interface DirectReferralsResponseDto {
  referrals: TeamMemberDto[];
  total: number;
  hasMore: boolean;
}

/**
 * 我的团队信息响应
 */
export interface MyTeamInfoDto {
  accountSequence: string;
  personalPlantingCount: number;
  teamPlantingCount: number;
  directReferralCount: number;
}

@Injectable()
export class GetTeamTreeQuery {
  constructor(
    @Inject(SYNCED_DATA_REPOSITORY)
    private readonly syncedDataRepository: ISyncedDataRepository,
  ) {}

  /**
   * 获取当前用户的团队信息
   */
  async getMyTeamInfo(accountSequence: string): Promise<MyTeamInfoDto> {
    // 获取个人认种棵数
    const personalPlantingCount = await this.syncedDataRepository.getTotalTreesByAccountSequence(accountSequence);

    // 获取直推数量
    const directReferrals = await this.syncedDataRepository.findDirectReferrals(accountSequence);

    // 获取团队认种棵数（伞下各级总和）
    const teamTreesByLevel = await this.syncedDataRepository.getTeamTreesByLevel(accountSequence, 15);
    let teamPlantingCount = 0;
    teamTreesByLevel.forEach((count) => {
      teamPlantingCount += count;
    });

    return {
      accountSequence,
      personalPlantingCount,
      teamPlantingCount,
      directReferralCount: directReferrals.length,
    };
  }

  /**
   * 获取指定用户的直推列表
   */
  async getDirectReferrals(
    accountSequence: string,
    limit: number = 100,
    offset: number = 0,
  ): Promise<DirectReferralsResponseDto> {
    // 获取所有直推
    const allDirectReferrals = await this.syncedDataRepository.findDirectReferrals(accountSequence);

    // 分页
    const total = allDirectReferrals.length;
    const paginatedReferrals = allDirectReferrals.slice(offset, offset + limit);

    // 获取每个直推成员的详细信息
    const referrals: TeamMemberDto[] = await Promise.all(
      paginatedReferrals.map(async (ref) => {
        return this.getTeamMemberInfo(ref.accountSequence);
      }),
    );

    return {
      referrals,
      total,
      hasMore: offset + limit < total,
    };
  }

  /**
   * 获取团队成员信息
   */
  private async getTeamMemberInfo(accountSequence: string): Promise<TeamMemberDto> {
    // 获取个人认种棵数
    const personalPlantingCount = await this.syncedDataRepository.getTotalTreesByAccountSequence(accountSequence);

    // 获取直推数量
    const directReferrals = await this.syncedDataRepository.findDirectReferrals(accountSequence);

    // 获取团队认种棵数
    const teamTreesByLevel = await this.syncedDataRepository.getTeamTreesByLevel(accountSequence, 15);
    let teamPlantingCount = 0;
    teamTreesByLevel.forEach((count) => {
      teamPlantingCount += count;
    });

    return {
      accountSequence,
      personalPlantingCount,
      teamPlantingCount,
      directReferralCount: directReferrals.length,
    };
  }
}
