import { DomainError } from '@/shared/exceptions/domain.exception';
import * as bip39 from '@scure/bip39';
import { wordlist } from '@scure/bip39/wordlists/english';

export class Mnemonic {
  constructor(public readonly value: string) {
    if (!bip39.validateMnemonic(value, wordlist)) {
      throw new DomainError('助记词格式错误');
    }
  }

  static generate(): Mnemonic {
    const mnemonic = bip39.generateMnemonic(wordlist, 128);
    return new Mnemonic(mnemonic);
  }

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

  toSeed(): Uint8Array {
    return bip39.mnemonicToSeedSync(this.value);
  }

  getWords(): string[] {
    return this.value.split(' ');
  }

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