package roomapi

import (
	"context"
	"errors"
	"testing"

	"hyapp/services/gateway-service/internal/appconfig"
)

type fakeGiftComboConfigReader struct {
	config appconfig.GiftComboConfig
	err    error
}

func (f fakeGiftComboConfigReader) GiftComboConfig(context.Context, string) (appconfig.GiftComboConfig, error) {
	return f.config, f.err
}

func TestRoomGiftComboConfigAssignsStableRolloutAndDisablesBatchingForHoldback(t *testing.T) {
	config := appconfig.DefaultGiftComboConfig()
	bucket := giftComboRolloutBucket("lalu", 42)
	config.RolloutBasisPoints = int32(bucket)
	handler := &Handler{giftComboReader: fakeGiftComboConfigReader{config: config}}

	resolved, err := handler.roomGiftComboConfig(context.Background(), "lalu", 42)
	if err != nil {
		t.Fatalf("roomGiftComboConfig failed: %v", err)
	}
	if resolved.Enabled || resolved.APIVersion != 2 {
		t.Fatalf("holdback must disable only micro-batching while preserving the V2 contract: %+v", resolved)
	}
	if got := giftComboRolloutBucket(" LALU ", 42); got != bucket {
		t.Fatalf("rollout bucket must be normalized and stable: got=%d want=%d", got, bucket)
	}
}

func TestRoomGiftComboConfigReadFailureDisablesBatching(t *testing.T) {
	handler := &Handler{giftComboReader: fakeGiftComboConfigReader{err: errors.New("admin db unavailable")}}
	resolved, err := handler.roomGiftComboConfig(context.Background(), "lalu", 42)
	if err == nil || resolved.Enabled || resolved.APIVersion != 2 || resolved.MaxPendingBatches <= 0 {
		t.Fatalf("remote read outage must disable batching without downgrading the V2 contract: config=%+v err=%v", resolved, err)
	}
}
