package cybersecurity

import (
	"fmt"

	"golang.org/x/crypto/nacl/box"
)

// OpenKeyBox decrypts a sealed box produced by SealKeyBox using the recipient's X25519 keypair.
// kexPub and kexPriv must each be exactly 32 bytes and correspond to the public key
// passed to SealKeyBox as recipientKexPub.
// Returns an error if decryption or authentication fails.
func OpenKeyBox(kexPub, kexPriv, sealedMsg []byte) ([]byte, error) {
	if len(kexPub) != 32 {
		return nil, fmt.Errorf("open_key_box: kexPub must be 32 bytes, got %d", len(kexPub))
	}
	if len(kexPriv) != 32 {
		return nil, fmt.Errorf("open_key_box: kexPriv must be 32 bytes, got %d", len(kexPriv))
	}

	var pub [32]byte
	var priv [32]byte
	copy(pub[:], kexPub)
	copy(priv[:], kexPriv)

	plaintext, ok := box.OpenAnonymous(nil, sealedMsg, &pub, &priv)
	if !ok {
		return nil, fmt.Errorf("open_key_box: decryption failed (authentication error or corrupted message)")
	}

	return plaintext, nil
}
