package system

import (
	"context"
	"encoding/json"
	"testing"

	"kra/internal/biz"
	"kra/internal/integration/runtimeconfig"
)

type integrationRuntimeTestProvider struct {
	*Data
	store *runtimeconfig.Store
}

func (p *integrationRuntimeTestProvider) IntegrationRuntime() *runtimeconfig.Store { return p.store }

func TestIntegrationConfigSavePublishesUnmaskedRuntimeValues(t *testing.T) {
	db, err := openWithDriver("sqlite", "file:"+t.Name()+"?mode=memory&cache=shared")
	if err != nil {
		t.Fatal(err)
	}
	if err = db.AutoMigrate(&integrationConfigPO{}); err != nil {
		t.Fatal(err)
	}
	provider := &integrationRuntimeTestProvider{Data: &Data{gormDB: newReloadableDB(db, nil)}, store: runtimeconfig.NewStore()}
	repo := &integrationConfigRepo{data: provider}

	values := biz.DefaultIntegrationConfig(biz.IntegrationKindMQ, "rabbitmq")
	values["password"] = "runtime-secret"
	raw, _ := json.Marshal(values)
	if err = repo.SaveIntegrationConfig(context.Background(), &biz.IntegrationConfig{Kind: biz.IntegrationKindMQ, Provider: "rabbitmq", Enabled: true, Values: raw}); err != nil {
		t.Fatal(err)
	}

	values["password"] = "******"
	raw, _ = json.Marshal(values)
	if err = repo.SaveIntegrationConfig(context.Background(), &biz.IntegrationConfig{Kind: biz.IntegrationKindMQ, Provider: "rabbitmq", Enabled: true, Values: raw}); err != nil {
		t.Fatal(err)
	}
	active, ok := provider.store.Get(biz.IntegrationKindMQ, "rabbitmq")
	if !ok || !active.Enabled {
		t.Fatalf("runtime config = %#v, ok=%v", active, ok)
	}
	stored := map[string]any{}
	if err = json.Unmarshal(active.Values, &stored); err != nil {
		t.Fatal(err)
	}
	if stored["password"] != "runtime-secret" {
		t.Fatalf("runtime password = %#v", stored["password"])
	}
}
