/**
 * ReferralCode Value Object
 * 格式: GNX + 5位大写字母数字 (共8位, 去除易混淆字符 0/O/I/1)
 */
export class ReferralCode {
  private static readonly ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
  private static readonly PATTERN = /^[A-Z0-9]{6,20}$/;

  private constructor(public readonly value: string) {
    if (!ReferralCode.PATTERN.test(value)) {
      throw new Error(`推荐码格式无效: ${value}`);
    }
  }

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

  /**
   * 基于 userId 生成确定性推荐码 (GNX + 5位随机字符)
   * 调用方应检查唯一性后重试
   */
  static generate(): ReferralCode {
    const prefix = 'GNX';
    let suffix = '';
    for (let i = 0; i < 5; i++) {
      suffix += ReferralCode.ALPHABET[Math.floor(Math.random() * ReferralCode.ALPHABET.length)];
    }
    return new ReferralCode(`${prefix}${suffix}`);
  }

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

  toString(): string {
    return this.value;
  }
}
