package integration

import (
	"encoding/json"
	"strings"
	"testing"

	"kra/internal/integration/runtimeconfig"
)

func TestConnectivityTesterRestoreMaskedSecrets(t *testing.T) {
	store := runtimeconfig.NewStore()
	store.Set(runtimeconfig.Config{
		Kind:     "mq",
		Provider: "rabbitmq",
		Enabled:  true,
		Values:   json.RawMessage(`{"username":"stored-user","password":"stored-secret"}`),
	})
	tester := NewConnectivityTester(store)

	t.Run("restores masked secret from active config", func(t *testing.T) {
		values := map[string]any{
			"username": "candidate-user",
			"password": "******",
		}

		if err := tester.restoreMaskedSecrets(" MQ ", " RabbitMQ ", values); err != nil {
			t.Fatalf("restoreMaskedSecrets() error = %v", err)
		}
		if got := values["password"]; got != "stored-secret" {
			t.Fatalf("password = %q, want stored secret", got)
		}
		if got := values["username"]; got != "candidate-user" {
			t.Fatalf("username = %q, want candidate value", got)
		}
	})

	t.Run("keeps newly entered secret", func(t *testing.T) {
		values := map[string]any{"password": "new-secret"}

		if err := tester.restoreMaskedSecrets("mq", "rabbitmq", values); err != nil {
			t.Fatalf("restoreMaskedSecrets() error = %v", err)
		}
		if got := values["password"]; got != "new-secret" {
			t.Fatalf("password = %q, want newly entered secret", got)
		}
	})

	t.Run("does not treat non-secret fields as masked secrets", func(t *testing.T) {
		values := map[string]any{
			"username": "******",
			"password": "new-secret",
		}

		if err := tester.restoreMaskedSecrets("mq", "rabbitmq", values); err != nil {
			t.Fatalf("restoreMaskedSecrets() error = %v", err)
		}
		if got := values["username"]; got != "******" {
			t.Fatalf("username = %q, want unchanged masked-looking value", got)
		}
	})
}

func TestConnectivityTesterRestoreMaskedSecretsRequiresStoredSecret(t *testing.T) {
	tester := NewConnectivityTester(runtimeconfig.NewStore())
	values := map[string]any{"password": "******"}

	err := tester.restoreMaskedSecrets("mq", "rabbitmq", values)
	if err == nil {
		t.Fatal("restoreMaskedSecrets() error = nil, want missing secret error")
	}
	if !strings.Contains(err.Error(), "password") || !strings.Contains(err.Error(), "重新填写") {
		t.Fatalf("restoreMaskedSecrets() error = %q, want actionable password message", err)
	}
	if got := values["password"]; got != "******" {
		t.Fatalf("password = %q, want masked value left unchanged after error", got)
	}
}
