package store

import "testing"

func TestResolveEffectiveBillingConfigKeepsPricingRulesAuthoritative(t *testing.T) {
	tests := []struct {
		name  string
		input EffectiveBillingConfigInput
		want  float64
	}{
		{
			name: "inherited rule replaces stale platform snapshot",
			input: EffectiveBillingConfigInput{
				BaseConfig:                videoBillingConfig(100),
				LegacyPlatformModelConfig: videoBillingConfig(100),
				InheritedRuleSetConfig:    videoBillingConfig(416),
			},
			want: 416,
		},
		{
			name: "legacy snapshot remains a fallback without a rule",
			input: EffectiveBillingConfigInput{
				BaseConfig:                videoBillingConfig(100),
				LegacyPlatformModelConfig: videoBillingConfig(125),
			},
			want: 125,
		},
		{
			name: "model rule remains an explicit pricing exception",
			input: EffectiveBillingConfigInput{
				BaseConfig:                videoBillingConfig(100),
				LegacyPlatformModelConfig: videoBillingConfig(125),
				InheritedRuleSetConfig:    videoBillingConfig(416),
				ModelRuleSetConfig:        videoBillingConfig(500),
			},
			want: 500,
		},
	}

	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			config := ResolveEffectiveBillingConfig(test.input)
			video, ok := config["video"].(map[string]any)
			if !ok {
				t.Fatalf("expected video billing config, got %#v", config)
			}
			if got := video["basePrice"]; got != test.want {
				t.Fatalf("video base price = %#v, want %v", got, test.want)
			}
		})
	}
}

func TestResolveEffectiveBillingConfigAppliesOverrideLast(t *testing.T) {
	config := ResolveEffectiveBillingConfig(EffectiveBillingConfigInput{
		InheritedRuleSetConfig: videoBillingConfig(416),
		Override:               videoBillingConfig(600),
	})
	video, ok := config["video"].(map[string]any)
	if !ok || video["basePrice"] != float64(600) {
		t.Fatalf("expected override price 600, got %#v", config)
	}
}

func TestResolveEffectiveBillingConfigPreservesBaseResourcesMissingFromRuleSet(t *testing.T) {
	config := ResolveEffectiveBillingConfig(EffectiveBillingConfigInput{
		BaseConfig: map[string]any{
			"music": map[string]any{"basePrice": float64(20)},
			"audio": map[string]any{"basePrice": float64(1)},
			"video": map[string]any{"basePrice": float64(100)},
		},
		InheritedRuleSetConfig: map[string]any{
			"video": map[string]any{"basePrice": float64(416)},
		},
	})

	assertBillingBasePrice(t, config, "music", 20)
	assertBillingBasePrice(t, config, "audio", 1)
	assertBillingBasePrice(t, config, "video", 416)
}

func assertBillingBasePrice(t *testing.T, config map[string]any, resource string, want float64) {
	t.Helper()
	resourceConfig, ok := config[resource].(map[string]any)
	if !ok || resourceConfig["basePrice"] != want {
		t.Fatalf("%s base price = %#v, want %v", resource, config[resource], want)
	}
}

func videoBillingConfig(basePrice float64) map[string]any {
	return map[string]any{
		"video": map[string]any{"basePrice": basePrice},
	}
}
