/**
 * 手机号值对象
 * 中国大陆手机号格式验证
 */
export class Phone {
  private static readonly PATTERN = /^1[3-9]\d{9}$/;

  constructor(public readonly value: string) {
    if (!this.isValid(value)) {
      throw new Error(`手机号格式无效: ${value}`);
    }
  }

  private isValid(value: string): boolean {
    return Phone.PATTERN.test(value);
  }

  static create(value: string): Phone {
    return new Phone(value);
  }

  static isValidFormat(value: string): boolean {
    return Phone.PATTERN.test(value);
  }

  /**
   * 获取脱敏后的手机号（前3后4）
   */
  get masked(): string {
    return this.value.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
  }

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

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