package docforge

import "testing"

// fakeResolver is a test double: it owns a namespace, populates a fixed
// set of key/value pairs, and advertises a fixed catalogue.
type fakeResolver struct {
	ns      string
	values  map[string]string
	catalog []VariableKey
}

func (f fakeResolver) Namespace() string   { return f.ns }
func (f fakeResolver) Keys() []VariableKey { return f.catalog }
func (f fakeResolver) Populate(bag PlaceholderMap) {
	for k, v := range f.values {
		bag[k] = v
	}
}

func TestResolverSet_BuildBagMergesDisjointNamespaces(t *testing.T) {
	set := NewResolverSet(
		fakeResolver{ns: "a", values: map[string]string{"a.x": "1", "a.y": "2"}},
		fakeResolver{ns: "b", values: map[string]string{"b.z": "3"}},
	)
	bag := set.BuildBag()
	if len(bag) != 3 {
		t.Fatalf("bag size = %d; want 3", len(bag))
	}
	for k, want := range map[string]string{"a.x": "1", "a.y": "2", "b.z": "3"} {
		if bag[k] != want {
			t.Errorf("bag[%q] = %q; want %q", k, bag[k], want)
		}
	}
}

func TestResolverSet_AddAndCatalogueOrder(t *testing.T) {
	set := NewResolverSet(
		fakeResolver{ns: "a", catalog: []VariableKey{{Key: "a.x", Group: "a"}}},
	)
	set.Add(fakeResolver{ns: "b", catalog: []VariableKey{
		{Key: "b.y", Group: "b"},
		{Key: "b.z", Group: "b"},
	}})

	cat := set.Catalogue()
	gotOrder := make([]string, len(cat))
	for i, e := range cat {
		gotOrder[i] = e.Key
	}
	want := []string{"a.x", "b.y", "b.z"} // resolver order, then Keys() order
	if len(gotOrder) != len(want) {
		t.Fatalf("catalogue len = %d; want %d", len(gotOrder), len(want))
	}
	for i := range want {
		if gotOrder[i] != want[i] {
			t.Errorf("catalogue[%d] = %q; want %q", i, gotOrder[i], want[i])
		}
	}
}
