// Copyright (c) 2026 Alibaba Group and its affiliates

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at

//     http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package sdk

import (
	"testing"
)

func TestEncryptDecrypt(t *testing.T) {
	sessionKey := []byte("0123456789abcdef0123456789abcdef") // 32 bytes
	content := "Hello, World!"

	// Encrypt
	encrypted, err := encryptContent(content, sessionKey)
	if err != nil {
		t.Fatalf("encryptContent failed: %v", err)
	}

	if encrypted == "" {
		t.Fatal("encrypted content is empty")
	}

	// Decrypt
	decrypted, err := decryptContent(encrypted, sessionKey)
	if err != nil {
		t.Fatalf("decryptContent failed: %v", err)
	}

	if decrypted != content {
		t.Errorf("decrypted content mismatch: got %q, want %q", decrypted, content)
	}
}

func TestEncryptWithInvalidKey(t *testing.T) {
	invalidKey := []byte("short") // Too short
	content := "test"

	_, err := encryptContent(content, invalidKey)
	if err == nil {
		t.Error("encryptContent should fail with invalid key")
	}
}

func TestDecryptWithWrongKey(t *testing.T) {
	key1 := []byte("0123456789abcdef0123456789abcdef")
	key2 := []byte("fedcba9876543210fedcba9876543210")
	content := "test"

	// Encrypt with key1
	encrypted, err := encryptContent(content, key1)
	if err != nil {
		t.Fatalf("encryptContent failed: %v", err)
	}

	// Decrypt with key2 (wrong key)
	_, err = decryptContent(encrypted, key2)
	if err == nil {
		t.Error("decryptContent should fail with wrong key")
	}
}

func TestDecryptWithInvalidBase64(t *testing.T) {
	sessionKey := []byte("0123456789abcdef0123456789abcdef")
	invalidBase64 := "not-valid-base64!!!"

	_, err := decryptContent(invalidBase64, sessionKey)
	if err == nil {
		t.Error("decryptContent should fail with invalid base64")
	}
}

func TestEncryptEmptyString(t *testing.T) {
	sessionKey := []byte("0123456789abcdef0123456789abcdef")
	content := ""

	encrypted, err := encryptContent(content, sessionKey)
	if err != nil {
		t.Fatalf("encryptContent failed for empty string: %v", err)
	}

	decrypted, err := decryptContent(encrypted, sessionKey)
	if err != nil {
		t.Fatalf("decryptContent failed for empty string: %v", err)
	}

	if decrypted != content {
		t.Errorf("decrypted empty string mismatch: got %q, want %q", decrypted, content)
	}
}
