package cybersecurity

import (
	"fmt"

	"golang.org/x/crypto/chacha20poly1305"
)

// OpenAEAD decrypts a ciphertext produced by SealAEAD using ChaCha20-Poly1305.
// key must be exactly 32 bytes. nonce must match the one returned by SealAEAD.
// aad must match what was passed to SealAEAD (can be nil).
// Returns an error if authentication fails (tampered ciphertext, wrong key, or wrong aad).
func OpenAEAD(key, nonce, ciphertext, aad []byte) ([]byte, error) {
	if len(key) != chacha20poly1305.KeySize {
		return nil, fmt.Errorf("open_aead: key must be %d bytes, got %d", chacha20poly1305.KeySize, len(key))
	}

	aead, err := chacha20poly1305.New(key)
	if err != nil {
		return nil, fmt.Errorf("open_aead: create cipher: %w", err)
	}

	plaintext, err := aead.Open(nil, nonce, ciphertext, aad)
	if err != nil {
		return nil, fmt.Errorf("open_aead: authentication failed: %w", err)
	}

	return plaintext, nil
}
