package crypto

import (
	"crypto/rand"
	"testing"

	"github.com/stretchr/testify/require"
)

func newKey(t *testing.T) []byte {
	t.Helper()
	k := make([]byte, 32)
	_, err := rand.Read(k)
	require.NoError(t, err)
	return k
}

func TestEncryptDecrypt_RoundTrip(t *testing.T) {
	key := newKey(t)
	enc, err := NewEncryptor(key)
	require.NoError(t, err)

	plaintext := []byte("hello world; some secret")
	ct, err := enc.Encrypt(plaintext)
	require.NoError(t, err)
	require.NotEqual(t, plaintext, ct)

	pt, err := enc.Decrypt(ct)
	require.NoError(t, err)
	require.Equal(t, plaintext, pt)
}

func TestEncrypt_DifferentNoncesEachCall(t *testing.T) {
	enc, _ := NewEncryptor(newKey(t))
	c1, _ := enc.Encrypt([]byte("x"))
	c2, _ := enc.Encrypt([]byte("x"))
	require.NotEqual(t, c1, c2, "nonce 应每次不同，密文不应一致")
}

func TestDecrypt_TamperedCiphertext_Fails(t *testing.T) {
	enc, _ := NewEncryptor(newKey(t))
	ct, _ := enc.Encrypt([]byte("x"))
	ct[len(ct)-1] ^= 0xFF
	_, err := enc.Decrypt(ct)
	require.Error(t, err)
}

func TestNewEncryptor_RejectsBadKeySize(t *testing.T) {
	_, err := NewEncryptor([]byte{1, 2, 3})
	require.Error(t, err)
}
