import { randomInt } from 'crypto';

/**
 * SmsCode Value Object
 * 短信验证码值对象 — 安全生成 + 比对验证
 */
export class SmsCode {
  static readonly LENGTH = 6;
  private static readonly PATTERN = /^\d{6}$/;

  private constructor(public readonly value: string) {}

  /**
   * 使用 crypto 安全随机数生成 6 位验证码
   */
  static generate(): SmsCode {
    const code = randomInt(0, 1_000_000).toString().padStart(SmsCode.LENGTH, '0');
    return new SmsCode(code);
  }

  /**
   * 从已有字符串重建
   */
  static from(raw: string): SmsCode {
    if (!SmsCode.PATTERN.test(raw)) {
      throw new Error(`验证码格式无效: 必须为${SmsCode.LENGTH}位数字`);
    }
    return new SmsCode(raw);
  }

  /**
   * 验证输入是否匹配
   */
  matches(input: string): boolean {
    return this.value === input;
  }

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