package runtimeconfig

import (
	"encoding/json"
	"testing"
)

func TestStoreSetDeleteAndSubscribe(t *testing.T) {
	store := NewStore()
	updates := make(chan Config, 2)
	stop := store.Subscribe("mq", "rabbitmq", func(config Config) { updates <- config })
	defer stop()

	store.Set(Config{Kind: "MQ", Provider: "RabbitMQ", Enabled: true, Values: json.RawMessage(`{"host":"localhost"}`)})
	loaded, ok := store.Get("mq", "rabbitmq")
	if !ok || !loaded.Enabled || string(loaded.Values) != `{"host":"localhost"}` {
		t.Fatalf("loaded config = %#v, ok=%v", loaded, ok)
	}
	if update := <-updates; !update.Enabled {
		t.Fatalf("set update = %#v", update)
	}

	store.Delete("mq", "rabbitmq")
	if _, ok = store.Get("mq", "rabbitmq"); ok {
		t.Fatal("deleted config remained in store")
	}
	if update := <-updates; update.Enabled {
		t.Fatalf("delete update = %#v", update)
	}
}
