package cryptox

import (
	"encoding/base64"
	"fmt"
	"testing"
)

func TestKeyringDecryptsOldVersionAndEncryptsActiveVersion(t *testing.T) {
	oldKey := base64.StdEncoding.EncodeToString(make([]byte, 32))
	newBytes := make([]byte, 32)
	newBytes[0] = 1
	newKey := base64.StdEncoding.EncodeToString(newBytes)
	oldCipher, err := NewAESGCM(oldKey, 1, "test")
	if err != nil {
		t.Fatal(err)
	}
	oldEncrypted, _, err := oldCipher.Encrypt([]byte("secret"))
	if err != nil {
		t.Fatal(err)
	}
	keyring, err := NewKeyring(newKey, 2, fmt.Sprintf(`{"1":%q}`, oldKey), "test")
	if err != nil {
		t.Fatal(err)
	}
	plaintext, err := keyring.Decrypt(oldEncrypted, 1)
	if err != nil || string(plaintext) != "secret" {
		t.Fatalf("old key was not usable: %q, %v", plaintext, err)
	}
	newEncrypted, version, err := keyring.Encrypt([]byte("new-secret"))
	if err != nil || version != 2 {
		t.Fatalf("active version was not used: version=%d error=%v", version, err)
	}
	if _, err := oldCipher.Decrypt(newEncrypted, version); err == nil {
		t.Fatal("old cipher must not decrypt the new version")
	}
}
