import { ReferralCode, ReferralChain, UserId } from '../../value-objects';
import { DomainEvent, ReferralRelationshipCreatedEvent } from '../../events';

export interface ReferralRelationshipProps {
  id: bigint;
  userId: bigint;
  accountSequence: string;  // 格式: D + YYMMDD + 5位序号
  referrerId: bigint | null;
  referralCode: string;        // 用户自己的推荐码
  usedReferralCode: string | null;  // 用户使用的推荐码（推荐人的推荐码）
  referralChain: bigint[];
  createdAt: Date;
  updatedAt: Date;
}

/**
 * 推荐关系聚合根
 *
 * 职责:
 * - 管理用户之间的推荐关系
 * - 生成和验证推荐码
 * - 维护推荐链
 */
export class ReferralRelationship {
  private _domainEvents: DomainEvent[] = [];

  private constructor(
    private readonly _id: bigint,
    private readonly _userId: UserId,
    private readonly _accountSequence: string,  // 格式: D + YYMMDD + 5位序号
    private readonly _referrerId: UserId | null,
    private readonly _referralCode: ReferralCode,
    private readonly _usedReferralCode: ReferralCode | null,  // 用户使用的推荐码（推荐人的推荐码）
    private readonly _referralChain: ReferralChain,
    private readonly _createdAt: Date,
    private _updatedAt: Date,
  ) {}

  // Getters
  get id(): bigint {
    return this._id;
  }
  get userId(): bigint {
    return this._userId.value;
  }
  get accountSequence(): string {
    return this._accountSequence;
  }
  get referrerId(): bigint | null {
    return this._referrerId?.value ?? null;
  }
  get referralCode(): string {
    return this._referralCode.value;
  }
  get usedReferralCode(): string | null {
    return this._usedReferralCode?.value ?? null;
  }
  get referralChain(): bigint[] {
    return this._referralChain.toArray();
  }
  get createdAt(): Date {
    return this._createdAt;
  }
  get updatedAt(): Date {
    return this._updatedAt;
  }
  get domainEvents(): DomainEvent[] {
    return [...this._domainEvents];
  }

  /**
   * 创建新的推荐关系 (用户注册时)
   * @param userId 新用户ID
   * @param accountSequence 新用户账户序号
   * @param userReferralCode 用户自己的推荐码（由 identity-service 生成，直接传入）
   * @param referrerId 推荐人ID（可选）
   * @param referrerReferralCode 推荐人的推荐码（可选，如果有推荐人则必须提供）
   * @param parentReferralChain 推荐人的推荐链
   */
  static create(
    userId: bigint,
    accountSequence: string,  // 格式: D + YYMMDD + 5位序号
    userReferralCode: string, // 用户的推荐码（由 identity-service 生成）
    referrerId: bigint | null,
    referrerReferralCode: string | null,  // 推荐人的推荐码
    parentReferralChain: bigint[] = [],
  ): ReferralRelationship {
    const userIdVo = UserId.create(userId);
    const referrerIdVo = referrerId ? UserId.create(referrerId) : null;
    const referralCode = ReferralCode.create(userReferralCode);  // 使用传入的推荐码，不再生成
    const usedReferralCode = referrerReferralCode ? ReferralCode.create(referrerReferralCode) : null;
    const referralChain = ReferralChain.create(referrerId, parentReferralChain);
    const now = new Date();

    const relationship = new ReferralRelationship(
      0n, // ID will be assigned by database
      userIdVo,
      accountSequence,
      referrerIdVo,
      referralCode,
      usedReferralCode,
      referralChain,
      now,
      now,
    );

    // 发布领域事件
    relationship._domainEvents.push(
      new ReferralRelationshipCreatedEvent(
        userId,
        referrerId,
        referralCode.value,
        referralChain.toArray(),
      ),
    );

    return relationship;
  }

  /**
   * 从持久化数据重建
   */
  static reconstitute(props: ReferralRelationshipProps): ReferralRelationship {
    return new ReferralRelationship(
      props.id,
      UserId.create(props.userId),
      props.accountSequence,
      props.referrerId ? UserId.create(props.referrerId) : null,
      ReferralCode.create(props.referralCode),
      props.usedReferralCode ? ReferralCode.create(props.usedReferralCode) : null,
      ReferralChain.fromArray(props.referralChain),
      props.createdAt,
      props.updatedAt,
    );
  }

  /**
   * 获取直接推荐人
   */
  getDirectReferrer(): bigint | null {
    return this._referralChain.directReferrer;
  }

  /**
   * 获取指定层级的上级
   */
  getReferrerAtLevel(level: number): bigint | null {
    return this._referralChain.getReferrerAtLevel(level);
  }

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

  /**
   * 推荐链深度
   */
  getChainDepth(): number {
    return this._referralChain.depth;
  }

  /**
   * 清除领域事件
   */
  clearDomainEvents(): void {
    this._domainEvents = [];
  }

  /**
   * 转换为持久化格式
   */
  toPersistence(): ReferralRelationshipProps {
    return {
      id: this._id,
      userId: this._userId.value,
      accountSequence: this._accountSequence,
      referrerId: this._referrerId?.value ?? null,
      referralCode: this._referralCode.value,
      usedReferralCode: this._usedReferralCode?.value ?? null,
      referralChain: this._referralChain.toArray(),
      createdAt: this._createdAt,
      updatedAt: this._updatedAt,
    };
  }
}
