package repository

import (
	"encoding/base64"
	"strings"
	"testing"

	"apps/backend/internal/lib/secretbox"
	"apps/backend/internal/module/member/domain"
)

func repositoryTestCodec(t *testing.T) *secretbox.Codec {
	t.Helper()
	c, err := secretbox.New("repo-test", base64.StdEncoding.EncodeToString([]byte("0123456789abcdef0123456789abcdef")))
	if err != nil {
		t.Fatal(err)
	}
	return c
}

func TestSettingsTransformEncryptsAllSecretsWithoutMutatingCaller(t *testing.T) {
	codec := repositoryTestCodec(t)
	original := &domain.UserSettings{
		UID: 7, Provider: "xai", APIKey: "legacy-key", ExaAPIKey: "exa-key",
		ProviderAPIKeys: map[string]string{"xai": "xai-key", "opencode-go": "oc-key", "empty": ""},
	}
	encrypted, err := encryptSettings(codec, 7, original)
	if err != nil {
		t.Fatal(err)
	}
	if original.APIKey != "legacy-key" || original.ExaAPIKey != "exa-key" || original.ProviderAPIKeys["xai"] != "xai-key" {
		t.Fatal("caller settings were mutated")
	}
	for name, value := range map[string]string{
		"api": encrypted.APIKey, "exa": encrypted.ExaAPIKey,
		"xai": encrypted.ProviderAPIKeys["xai"], "opencode": encrypted.ProviderAPIKeys["opencode-go"],
	} {
		if !strings.HasPrefix(value, "enc:v1:repo-test:") {
			t.Fatalf("%s was not encrypted: %q", name, value)
		}
	}
	if encrypted.ProviderAPIKeys["empty"] != "" {
		t.Fatal("empty key should remain empty")
	}
	decrypted, err := decryptSettings(codec, 7, encrypted)
	if err != nil {
		t.Fatal(err)
	}
	if decrypted.APIKey != "legacy-key" || decrypted.ExaAPIKey != "exa-key" || decrypted.ProviderAPIKeys["opencode-go"] != "oc-key" {
		t.Fatalf("unexpected plaintext: %#v", decrypted)
	}
}

func TestSettingsTransformLegacyAndMissingCodecBehavior(t *testing.T) {
	legacy := &domain.UserSettings{UID: 8, Provider: "xai", APIKey: "plain", ProviderAPIKeys: map[string]string{"xai": "plain-map"}}
	got, err := decryptSettings(nil, 8, legacy)
	if err != nil || got.APIKey != "plain" || got.ProviderAPIKeys["xai"] != "plain-map" {
		t.Fatalf("legacy read = %#v, %v", got, err)
	}
	if _, err := encryptSettings(nil, 8, legacy); err == nil {
		t.Fatal("nonempty secret save without codec must fail")
	}
	if _, err := encryptSettings(nil, 8, &domain.UserSettings{UID: 8, ProviderAPIKeys: map[string]string{}}); err != nil {
		t.Fatalf("empty settings save should remain constructible: %v", err)
	}

	codec := repositoryTestCodec(t)
	encrypted, err := encryptSettings(codec, 8, legacy)
	if err != nil {
		t.Fatal(err)
	}
	if _, err := decryptSettings(nil, 8, encrypted); err == nil {
		t.Fatal("encrypted read without codec must fail")
	}
	if _, err := decryptSettings(codec, 9, encrypted); err == nil {
		t.Fatal("ciphertext must not move between users")
	}
}
