export class ReferralCode {
  private constructor(public readonly value: string) {
    if (!value || value.length < 6 || value.length > 20) {
      throw new Error('推荐码长度必须在6-20个字符之间');
    }
    if (!/^[A-Z0-9]+$/.test(value)) {
      throw new Error('推荐码只能包含大写字母和数字');
    }
  }

  static create(value: string): ReferralCode {
    return new ReferralCode(value.toUpperCase());
  }

  static generate(userId: bigint): ReferralCode {
    // 生成规则: 前缀 + 用户ID哈希 + 随机字符
    const prefix = 'RWA';
    const userIdHash = userId.toString(36).toUpperCase().slice(-3).padStart(3, '0');
    const random = Math.random().toString(36).toUpperCase().slice(2, 6).padEnd(4, '0');
    return new ReferralCode(`${prefix}${userIdHash}${random}`);
  }

  equals(other: ReferralCode): boolean {
    return this.value === other.value;
  }
}
