/**
 * 用户详情查询仓储接口
 * 用于 admin-web 用户详情页面的数据查询
 */

// ============================================================================
// 推荐关系相关
// ============================================================================

export interface ReferralInfo {
  userId: bigint;
  accountSequence: string;
  myReferralCode: string;
  usedReferralCode: string | null;
  referrerId: bigint | null;
  ancestorPath: bigint[];
  depth: number;
  directReferralCount: number;
  activeDirectCount: number;
}

export interface ReferralNode {
  userId: bigint;
  accountSequence: string;
  nickname: string | null;
  avatarUrl: string | null;
  personalAdoptionCount: number;
  teamAdoptionCount: number; // 团队认种量（包括本人和所有下级）
  depth: number;
  directReferralCount: number;
}

// ============================================================================
// 认种相关
// ============================================================================

export interface PlantingSummary {
  totalOrders: number;
  totalTreeCount: number;
  totalAmount: string; // 格式化后的金额字符串
  effectiveTreeCount: number;
  pendingTreeCount: number;
  firstPlantingAt: Date | null;
  lastPlantingAt: Date | null;
}

export interface PlantingLedgerItem {
  orderId: bigint;
  orderNo: string;
  treeCount: number;
  totalAmount: string; // 格式化后的金额字符串
  status: string;
  selectedProvince: string | null;
  selectedCity: string | null;
  createdAt: Date;
  paidAt: Date | null;
  fundAllocatedAt: Date | null;
  miningEnabledAt: Date | null;
}

export interface PlantingLedgerResult {
  items: PlantingLedgerItem[];
  total: number;
  page: number;
  pageSize: number;
  totalPages: number;
}

// ============================================================================
// 钱包相关
// ============================================================================

export interface WalletSummary {
  usdtAvailable: string;
  usdtFrozen: string;
  dstAvailable: string;
  dstFrozen: string;
  bnbAvailable: string;
  bnbFrozen: string;
  ogAvailable: string;
  ogFrozen: string;
  rwadAvailable: string;
  rwadFrozen: string;
  hashpower: string;
  pendingUsdt: string;
  pendingHashpower: string;
  settleableUsdt: string;
  settleableHashpower: string;
  settledTotalUsdt: string;
  settledTotalHashpower: string;
  expiredTotalUsdt: string;
  expiredTotalHashpower: string;
}

export interface WalletLedgerItem {
  entryId: bigint;
  entryType: string;
  assetType: string;
  amount: string; // 格式化后的金额字符串
  balanceAfter: string | null; // 格式化后的余额字符串
  refOrderId: string | null;
  refTxHash: string | null;
  memo: string | null;
  createdAt: Date;
}

export interface WalletLedgerResult {
  items: WalletLedgerItem[];
  total: number;
  page: number;
  pageSize: number;
  totalPages: number;
}

export interface WalletLedgerFilters {
  assetType?: string;
  entryType?: string;
  startDate?: Date;
  endDate?: Date;
}

// ============================================================================
// 授权相关
// ============================================================================

export interface AuthorizationRole {
  id: string;
  roleType: string;
  regionCode: string;
  regionName: string;
  displayTitle: string;
  status: string;
  benefitActive: boolean;
  benefitActivatedAt: Date | null;
  authorizedAt: Date | null;
  authorizedBy: string | null;
  initialTargetTreeCount: number;
  monthlyTargetType: string;
  lastAssessmentMonth: string | null;
  monthlyTreesAdded: number;
  officePhotoUrls: string[];
  createdAt: Date;
}

export interface MonthlyAssessment {
  id: string;
  authorizationId: string;
  roleType: string;
  regionCode: string;
  assessmentMonth: string;
  monthIndex: number;
  monthlyTarget: number;
  monthlyCompleted: number;
  cumulativeTarget: number;
  cumulativeCompleted: number;
  result: string;
  rankingInRegion: number | null;
  isFirstPlace: boolean;
  isBypassed: boolean;
  completedAt: Date | null;
  assessedAt: Date | null;
}

export interface SystemAccountLedger {
  ledgerId: bigint;
  accountId: bigint;
  accountType: string;
  entryType: string;
  amount: string; // 格式化后的金额字符串
  balanceAfter: string; // 格式化后的余额字符串
  sourceOrderId: bigint | null;
  sourceRewardId: bigint | null;
  txHash: string | null;
  memo: string | null;
  createdAt: Date;
}

// [2026-01-08] 新增：权益考核记录，独立于火柴人排名
export interface BenefitAssessment {
  id: string;
  authorizationId: string;
  roleType: string;
  regionCode: string;
  regionName: string;
  assessmentMonth: string;
  monthIndex: number;
  monthlyTarget: number;
  cumulativeTarget: number;
  treesCompleted: number;
  treesRequired: number;
  benefitActionTaken: string; // ACTIVATED, RENEWED, DEACTIVATED, NO_CHANGE
  previousBenefitStatus: boolean;
  newBenefitStatus: boolean;
  newValidUntil: Date | null;
  result: string;
  remarks: string | null;
  assessedAt: Date;
  createdAt: Date;
}

// ============================================================================
// 仓储接口
// ============================================================================

export const USER_DETAIL_QUERY_REPOSITORY = Symbol('USER_DETAIL_QUERY_REPOSITORY');

export interface IUserDetailQueryRepository {
  /**
   * 获取用户推荐关系信息
   */
  getReferralInfo(accountSequence: string): Promise<ReferralInfo | null>;

  /**
   * 获取用户推荐人链（向上）
   */
  getAncestors(accountSequence: string, depth: number): Promise<ReferralNode[]>;

  /**
   * 获取用户直推列表（向下）
   */
  getDirectReferrals(accountSequence: string): Promise<ReferralNode[]>;

  /**
   * 获取推荐人昵称
   */
  getReferrerNickname(referrerId: bigint): Promise<string | null>;

  /**
   * 获取认种汇总
   */
  getPlantingSummary(accountSequence: string): Promise<PlantingSummary | null>;

  /**
   * 获取认种分类账
   */
  getPlantingLedger(
    accountSequence: string,
    page: number,
    pageSize: number,
    startDate?: Date,
    endDate?: Date,
  ): Promise<PlantingLedgerResult>;

  /**
   * 获取钱包汇总
   */
  getWalletSummary(accountSequence: string): Promise<WalletSummary | null>;

  /**
   * 获取钱包分类账
   */
  getWalletLedger(
    accountSequence: string,
    page: number,
    pageSize: number,
    filters?: WalletLedgerFilters,
  ): Promise<WalletLedgerResult>;

  /**
   * 获取授权角色列表
   */
  getAuthorizationRoles(accountSequence: string): Promise<AuthorizationRole[]>;

  /**
   * 获取月度考核记录
   */
  getMonthlyAssessments(accountSequence: string): Promise<MonthlyAssessment[]>;

  /**
   * 获取系统账户流水（用户相关的授权角色账户流水）
   */
  getSystemAccountLedger(accountSequence: string): Promise<SystemAccountLedger[]>;

  /**
   * [2026-01-08] 获取权益考核记录
   * 独立于火柴人排名（MonthlyAssessment），专门记录权益有效性考核历史
   */
  getBenefitAssessments(accountSequence: string): Promise<BenefitAssessment[]>;

  /**
   * 获取用户个人认种量（有效树数）
   */
  getPersonalAdoptionCount(accountSequence: string): Promise<number>;

  /**
   * 获取用户直推数量
   */
  getDirectReferralCount(accountSequence: string): Promise<number>;

  /**
   * 获取用户团队统计（团队地址数、团队认种量）
   * 团队包括所有直推和间推用户
   */
  getTeamStats(accountSequence: string): Promise<{ teamAddressCount: number; teamAdoptionCount: number }>;

  /**
   * 批量获取用户实时统计（用于用户列表页面）
   * 返回 Map<accountSequence, stats>
   */
  getBatchUserStats(accountSequences: string[]): Promise<Map<string, {
    personalAdoptionCount: number;
    teamAddressCount: number;
    teamAdoptionCount: number;
    provinceAdoptionCount: number;
    cityAdoptionCount: number;
  }>>;
}
