package appconfig

import "testing"

func TestStoredGiftComboConfigFromRequestPreservesExplicitKillSwitch(t *testing.T) {
	config, err := storedGiftComboConfigFromRequest(GiftComboConfigRequest{
		Enabled:              false,
		APIVersion:           2,
		WindowMS:             300,
		MaxGiftCountPerBatch: 999,
		MaxGiftUnitsPerBatch: 5_000,
		MaxInFlight:          2,
		MaxPendingBatches:    20,
		RetryMaxAttempts:     5,
		RetryBaseDelayMS:     250,
		RolloutBasisPoints:   5_000,
	})
	if err != nil {
		t.Fatalf("storedGiftComboConfigFromRequest failed: %v", err)
	}
	if config.Enabled || config.RolloutBasisPoints != 5_000 {
		t.Fatalf("explicit kill switch changed during normalization: %+v", config)
	}
}

func TestNormalizeStoredGiftComboConfigRejectsQueueWithoutBackpressure(t *testing.T) {
	config := defaultStoredGiftComboConfig()
	config.APIVersion = 1
	if _, err := normalizeStoredGiftComboConfig(config); err == nil {
		t.Fatal("apiVersion 1 must not turn the current Flutter back to the legacy HTTP contract")
	}
	config = defaultStoredGiftComboConfig()
	config.MaxInFlight = 3
	if _, err := normalizeStoredGiftComboConfig(config); err == nil {
		t.Fatal("maxInFlight above the server contract must be rejected")
	}
	config = defaultStoredGiftComboConfig()
	config.MaxPendingBatches = 0
	if _, err := normalizeStoredGiftComboConfig(config); err == nil {
		t.Fatal("unbounded/empty pending queue policy must be rejected")
	}
	config = defaultStoredGiftComboConfig()
	config.MaxInFlight = 2
	config.MaxPendingBatches = 1
	if _, err := normalizeStoredGiftComboConfig(config); err == nil {
		t.Fatal("pending queue smaller than in-flight concurrency must be rejected")
	}
}

func TestNormalizeStoredGiftComboConfigForReadPromotesLegacyVersionMarker(t *testing.T) {
	config := defaultStoredGiftComboConfig()
	config.APIVersion = 1
	resolved, err := normalizeStoredGiftComboConfigForRead(config)
	if err != nil {
		t.Fatalf("legacy stored config must remain readable: %v", err)
	}
	if resolved.APIVersion != 2 {
		t.Fatalf("legacy stored marker was not promoted to V2: %+v", resolved)
	}
}
