package secret

import (
	"os"
	"path/filepath"
	"testing"
)

func setupTestEnv(t *testing.T) {
	t.Helper()
	tmpDir := t.TempDir()
	origHome := os.Getenv("HOME")
	os.Setenv("HOME", tmpDir)
	t.Cleanup(func() { os.Setenv("HOME", origHome) })
	resetForTesting()
}

func TestEncryptDecryptRoundtrip(t *testing.T) {
	setupTestEnv(t)

	plaintext := "my-super-secret-api-key-12345"
	encrypted, err := Encrypt(plaintext)
	if err != nil {
		t.Fatalf("Encrypt failed: %v", err)
	}
	if encrypted == "" {
		t.Error("Encrypted should not be empty")
	}
	if encrypted == plaintext {
		t.Error("Encrypted should differ from plaintext")
	}

	decrypted, err := Decrypt(encrypted)
	if err != nil {
		t.Fatalf("Decrypt failed: %v", err)
	}
	if decrypted != plaintext {
		t.Errorf("Expected %s, got %s", plaintext, decrypted)
	}
}

func TestEncryptEmpty(t *testing.T) {
	enc, err := Encrypt("")
	if err != nil {
		t.Fatalf("Encrypt empty failed: %v", err)
	}
	if enc != "" {
		t.Error("Empty input should return empty output")
	}
}

func TestDecryptEmpty(t *testing.T) {
	dec, err := Decrypt("")
	if err != nil {
		t.Fatalf("Decrypt empty failed: %v", err)
	}
	if dec != "" {
		t.Error("Empty input should return empty output")
	}
}

func TestIsEncrypted(t *testing.T) {
	setupTestEnv(t)

	if IsEncrypted("") {
		t.Error("Empty string should not be encrypted")
	}
	if IsEncrypted("not-encrypted") {
		t.Error("Random string should not be encrypted")
	}

	enc, _ := Encrypt("test")
	if !IsEncrypted(enc) {
		t.Error("Encrypted string should be detected as encrypted")
	}
}

func TestKeyFileCreation(t *testing.T) {
	setupTestEnv(t)

	_, err := Encrypt("test")
	if err != nil {
		t.Fatalf("Encrypt failed: %v", err)
	}

	home, _ := os.UserHomeDir()
	keyPath := filepath.Join(home, ".muyue_key")
	if _, err := os.Stat(keyPath); os.IsNotExist(err) {
		t.Error("Key file should be created")
	}

	info, _ := os.Stat(keyPath)
	if info.Mode().Perm()&0077 != 0 {
		t.Error("Key file should have restrictive permissions")
	}
}

func TestDecryptInvalidBase64(t *testing.T) {
	setupTestEnv(t)

	_, _ = Encrypt("init")

	_, err := Decrypt("not-valid-base64!!!")
	if err == nil {
		t.Error("Should fail with invalid base64")
	}
}

func TestDifferentKeysProduceDifferentCiphertext(t *testing.T) {
	setupTestEnv(t)

	enc1, _ := Encrypt("same-input")
	resetForTesting()
	enc2, _ := Encrypt("same-input")

	if enc1 == enc2 {
		t.Error("Different keys should produce different ciphertext (different nonce)")
	}
}
