package core

import "testing"

func TestParseManagerConfig(t *testing.T) {
	cfg, err := parseManagerConfig(map[string]string{
		managerConfigKey: `
keyspaces:
  keyspace-a: analytics
  keyspace-b: main
pools:
  analytics:
    create: true
    templatePool: main
`,
	})
	if err != nil {
		t.Fatalf("parseManagerConfig returned error: %v", err)
	}

	if got := cfg.Keyspaces["keyspace-a"]; got != "analytics" {
		t.Fatalf("unexpected keyspace entry: %q", got)
	}
	if !cfg.Pools["analytics"].Create {
		t.Fatalf("expected analytics pool to be marked for creation")
	}
	if got := cfg.Pools["analytics"].TemplatePool; got != "main" {
		t.Fatalf("unexpected template pool: %q", got)
	}
}

func TestDesiredPoolsIncludesDefaultAndSpecializedPools(t *testing.T) {
	cfg := &ManagerConfig{
		Keyspaces: map[string]string{
			"keyspace-a": "analytics",
		},
		Pools: map[string]PoolSpec{
			"analytics": {Create: true},
		},
	}

	desired := cfg.DesiredPools("main")
	if _, ok := desired["main"]; !ok {
		t.Fatalf("default pool should always be present")
	}
	if spec, ok := desired["analytics"]; !ok {
		t.Fatalf("specialized pool should be present")
	} else if !spec.Create {
		t.Fatalf("pool spec should be preserved")
	}
}

func TestParseManagerConfigMissingKeyFallsBackToEmptyConfig(t *testing.T) {
	cfg, err := parseManagerConfig(map[string]string{})
	if err != nil {
		t.Fatalf("parseManagerConfig returned error: %v", err)
	}
	if len(cfg.Keyspaces) != 0 {
		t.Fatalf("expected empty keyspaces map, got %d entries", len(cfg.Keyspaces))
	}
	if len(cfg.Pools) != 0 {
		t.Fatalf("expected empty pools map, got %d entries", len(cfg.Pools))
	}
}

func TestKeyspacesOverrideDeprecatedSpecialize(t *testing.T) {
	cfg := &ManagerConfig{
		Keyspaces: map[string]string{
			"100": "analytics",
		},
		Specialize: map[string]string{
			"100": "legacy",
		},
	}

	mappings := cfg.keyspacePools()
	if got := mappings["100"]; got != "analytics" {
		t.Fatalf("expected keyspaces to override deprecated specialize, got %q", got)
	}
}
