import { bech32 } from 'bech32';

/**
 * Cosmos 地址值对象 (bech32 格式)
 * 支持 kava1..., dst1... 等地址格式
 */
export class CosmosAddress {
  private readonly _value: string;
  private readonly _prefix: string;

  private constructor(value: string, prefix: string) {
    this._value = value;
    this._prefix = prefix;
  }

  static create(value: string): CosmosAddress {
    try {
      const decoded = bech32.decode(value);
      return new CosmosAddress(value, decoded.prefix);
    } catch {
      throw new Error(`Invalid Cosmos address: ${value}`);
    }
  }

  static fromPrefixAndHash(prefix: string, hash20Bytes: Uint8Array): CosmosAddress {
    const words = bech32.toWords(Buffer.from(hash20Bytes));
    const address = bech32.encode(prefix, words);
    return new CosmosAddress(address, prefix);
  }

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

  get prefix(): string {
    return this._prefix;
  }

  get lowercase(): string {
    return this._value.toLowerCase();
  }

  equals(other: CosmosAddress): boolean {
    return this._value.toLowerCase() === other._value.toLowerCase();
  }

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