package credentials

import (
	"encoding/base64"
	"testing"
)

func TestEncryptDecryptOAuth(t *testing.T) {
	key := base64.StdEncoding.EncodeToString([]byte("0123456789abcdef0123456789abcdef"))
	manager, err := NewManager("v1:"+key, "v1")
	if err != nil {
		t.Fatalf("new manager: %v", err)
	}

	blob, err := manager.EncryptCredential(Credential{
		AuthType:      AuthOAuth2,
		Username:      "user@gmail.com",
		AccessToken:   "access-token",
		RefreshToken:  "refresh-token",
		OAuthProvider: "google",
	})
	if err != nil {
		t.Fatalf("encrypt oauth: %v", err)
	}

	cred, err := manager.DecryptCredential(blob)
	if err != nil {
		t.Fatalf("decrypt oauth: %v", err)
	}
	if !cred.IsOAuth() || cred.AccessToken != "access-token" {
		t.Fatalf("unexpected oauth cred: %+v", cred)
	}
}

func TestEncryptDecrypt(t *testing.T) {
	key := base64.StdEncoding.EncodeToString([]byte("0123456789abcdef0123456789abcdef"))
	manager, err := NewManager("v1:"+key, "v1")
	if err != nil {
		t.Fatalf("new manager: %v", err)
	}

	blob, err := manager.Encrypt("alice@example.com", "secret")
	if err != nil {
		t.Fatalf("encrypt: %v", err)
	}
	if !IsEncrypted(blob) {
		t.Fatalf("expected encrypted blob prefix")
	}

	username, password, err := manager.Decrypt(blob)
	if err != nil {
		t.Fatalf("decrypt: %v", err)
	}
	if username != "alice@example.com" || password != "secret" {
		t.Fatalf("unexpected decrypted credentials: %s/%s", username, password)
	}
}
