package main

import (
	"crypto/ed25519"
	"fmt"

	"github.com/mr-tron/base58"
)

type Keypair struct {
	PublicKey  ed25519.PublicKey
	PrivateKey ed25519.PrivateKey
}

func keypairFromSecretKey(privateKeyB58 string) (*Keypair, error) {
	secretKey, err := base58.Decode(privateKeyB58)
	if err != nil {
		return nil, fmt.Errorf("failed to decode private key: %w", err)
	}

	if len(secretKey) != 64 {
		return nil, fmt.Errorf("invalid secret key length: expected 64, got %d", len(secretKey))
	}

	privateKey := ed25519.PrivateKey(secretKey)
	publicKey := privateKey.Public().(ed25519.PublicKey)

	return &Keypair{
		PublicKey:  publicKey,
		PrivateKey: privateKey,
	}, nil
}

func (kp *Keypair) PublicKeyBase58() string {
	return base58.Encode(kp.PublicKey)
}

func signMessage(privateKey ed25519.PrivateKey, message []byte) string {
	signature := ed25519.Sign(privateKey, message)
	return base58.Encode(signature)
}
