/**
 * 短信验证码值对象
 */
export class SmsCode {
  private static readonly LENGTH = 6;
  private static readonly PATTERN = /^\d{6}$/;

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

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

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

  /**
   * 生成随机验证码
   */
  static generate(): SmsCode {
    const code = Math.random()
      .toString()
      .slice(2, 2 + SmsCode.LENGTH)
      .padEnd(SmsCode.LENGTH, '0');
    return new SmsCode(code);
  }

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

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