import { DomainError } from '@/shared/exceptions/domain.exception';

export class ReferralCode {
  constructor(public readonly value: string) {
    // 兼容 referral-service 的推荐码格式 (6-20位大写字母和数字)
    if (!/^[A-Z0-9]{6,20}$/.test(value)) {
      throw new DomainError('推荐码格式错误');
    }
  }

  static generate(): ReferralCode {
    // 生成6位随机推荐码（identity-service 本地生成）
    // 注：referral-service 会生成10位的推荐码，两者都兼容
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    let code = '';
    for (let i = 0; i < 6; i++) {
      code += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    return new ReferralCode(code);
  }

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

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