import * as bcrypt from 'bcryptjs';

export class Password {
  private constructor(private readonly hash: string) {}

  static async create(plaintext: string): Promise<Password> {
    if (plaintext.length < 8) {
      throw new Error('Password must be at least 8 characters');
    }
    if (plaintext.length > 128) {
      throw new Error('Password must not exceed 128 characters');
    }
    const hash = await bcrypt.hash(plaintext, 12);
    return new Password(hash);
  }

  static fromHash(hash: string): Password {
    return new Password(hash);
  }

  async verify(plaintext: string): Promise<boolean> {
    return bcrypt.compare(plaintext, this.hash);
  }

  get value(): string {
    return this.hash;
  }
}
