/**
 * 推荐链值对象
 * 存储从直接推荐人到根节点的用户ID列表
 */
export class ReferralChain {
  private static readonly MAX_DEPTH = 1000;

  private constructor(public readonly chain: bigint[]) {
    if (chain.length > ReferralChain.MAX_DEPTH) {
      throw new Error(`推荐链深度不能超过 ${ReferralChain.MAX_DEPTH}`);
    }
  }

  static create(referrerId: bigint | null, parentChain: bigint[] = []): ReferralChain {
    if (!referrerId) {
      return new ReferralChain([]);
    }

    // 新链 = [直接推荐人] + 父链的前 MAX_DEPTH - 1 个元素
    const newChain = [referrerId, ...parentChain.slice(0, this.MAX_DEPTH - 1)];
    return new ReferralChain(newChain);
  }

  static fromArray(chain: bigint[]): ReferralChain {
    return new ReferralChain([...chain]);
  }

  static empty(): ReferralChain {
    return new ReferralChain([]);
  }

  get depth(): number {
    return this.chain.length;
  }

  get directReferrer(): bigint | null {
    return this.chain[0] ?? null;
  }

  /**
   * 获取指定层级的推荐人
   * @param level 层级 (0 = 直接推荐人, 1 = 推荐人的推荐人, ...)
   */
  getReferrerAtLevel(level: number): bigint | null {
    return this.chain[level] ?? null;
  }

  /**
   * 获取所有上级 (用于团队统计更新)
   */
  getAllAncestors(): bigint[] {
    return [...this.chain];
  }

  toArray(): bigint[] {
    return [...this.chain];
  }
}
