/**
 * PublicKey Value Object
 *
 * ECDSA public key for MPC group.
 */

export class PublicKey {
  private readonly _keyBytes: Buffer;

  private constructor(keyBytes: Buffer) {
    this._keyBytes = keyBytes;
  }

  get bytes(): Buffer {
    return Buffer.from(this._keyBytes);
  }

  static create(keyBytes: Buffer): PublicKey {
    if (!keyBytes || keyBytes.length === 0) {
      throw new Error('Public key cannot be empty');
    }
    // ECDSA public key: 33 bytes (compressed) or 65 bytes (uncompressed)
    if (keyBytes.length !== 33 && keyBytes.length !== 65) {
      throw new Error('Invalid public key length. Expected 33 (compressed) or 65 (uncompressed) bytes');
    }
    return new PublicKey(keyBytes);
  }

  static fromHex(hex: string): PublicKey {
    if (!hex || hex.length === 0) {
      throw new Error('Public key hex string cannot be empty');
    }
    return PublicKey.create(Buffer.from(hex, 'hex'));
  }

  static fromBase64(base64: string): PublicKey {
    if (!base64 || base64.length === 0) {
      throw new Error('Public key base64 string cannot be empty');
    }
    return PublicKey.create(Buffer.from(base64, 'base64'));
  }

  toHex(): string {
    return this._keyBytes.toString('hex');
  }

  toBase64(): string {
    return this._keyBytes.toString('base64');
  }

  /**
   * Check if the public key is in compressed format
   */
  isCompressed(): boolean {
    return this._keyBytes.length === 33;
  }

  equals(other: PublicKey): boolean {
    return this._keyBytes.equals(other._keyBytes);
  }

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