package config

import "testing"

func TestMigrateV1ToV2Litellm(t *testing.T) {
	raw := map[string]any{
		"ai": map[string]any{
			"provider": "litellm",
			"embeddings": map[string]any{
				"model":      "text-embedding-3-small",
				"dimensions": 1536,
			},
			"metadata": map[string]any{
				"model":           "gpt-4o-mini",
				"temperature":     0.2,
				"fallback_models": []any{"gpt-4.1-mini"},
			},
			"litellm": map[string]any{
				"base_url": "http://localhost:4000/v1",
				"api_key":  "secret",
			},
		},
	}

	applied, err := Migrate(raw)
	if err != nil {
		t.Fatalf("Migrate() error = %v", err)
	}
	if len(applied) != 1 || applied[0].From != 1 || applied[0].To != 2 {
		t.Fatalf("applied = %+v, want [v1->v2]", applied)
	}
	if got := readVersion(raw); got != CurrentConfigVersion {
		t.Fatalf("version = %d, want %d", got, CurrentConfigVersion)
	}

	ai := mapValue(raw, "ai")
	providers := mapValue(ai, "providers")
	def := mapValue(providers, "default")
	if got := stringValue(def, "type"); got != "litellm" {
		t.Fatalf("providers.default.type = %q, want litellm", got)
	}
	if got := stringValue(def, "base_url"); got != "http://localhost:4000/v1" {
		t.Fatalf("providers.default.base_url = %q", got)
	}

	emb := mapValue(ai, "embeddings")
	embPrimary := mapValue(emb, "primary")
	if stringValue(embPrimary, "provider") != "default" || stringValue(embPrimary, "model") != "text-embedding-3-small" {
		t.Fatalf("embeddings.primary = %+v, want default/text-embedding-3-small", embPrimary)
	}

	meta := mapValue(ai, "metadata")
	metaPrimary := mapValue(meta, "primary")
	if stringValue(metaPrimary, "provider") != "default" || stringValue(metaPrimary, "model") != "gpt-4o-mini" {
		t.Fatalf("metadata.primary = %+v, want default/gpt-4o-mini", metaPrimary)
	}
	fallbacks, ok := meta["fallbacks"].([]any)
	if !ok || len(fallbacks) != 1 {
		t.Fatalf("metadata.fallbacks = %#v, want len=1", meta["fallbacks"])
	}
	firstFallback, ok := fallbacks[0].(map[string]any)
	if !ok {
		t.Fatalf("metadata.fallbacks[0] type = %T, want map[string]any", fallbacks[0])
	}
	if stringValue(firstFallback, "provider") != "default" || stringValue(firstFallback, "model") != "gpt-4.1-mini" {
		t.Fatalf("metadata fallback = %+v, want default/gpt-4.1-mini", firstFallback)
	}
}

func TestMigrateRejectsNewerVersion(t *testing.T) {
	raw := map[string]any{"version": CurrentConfigVersion + 1}

	_, err := Migrate(raw)
	if err == nil {
		t.Fatal("Migrate() error = nil, want error for newer config version")
	}
}
