package wheel

import (
	"fmt"
	"strings"
	"testing"

	domain "hyapp/services/activity-service/internal/domain/wheel"
)

func TestNormalizeRuleConfigForcesPropRTPValueToZero(t *testing.T) {
	config := NormalizeRuleConfig(domain.RuleConfig{
		WheelID:               "classic",
		DrawPriceCoins:        100,
		SettlementWindowDraws: 1000,
		Tiers: []domain.Tier{
			{TierID: "dress", RewardType: "dress", RewardID: "frame_1", RTPValueCoins: 999999, WeightPPM: 1, Enabled: true},
			{TierID: "prop", RewardType: "item", RewardID: "car_1", RTPValueCoins: 888888, WeightPPM: 1, Enabled: true},
			{TierID: "coin", RewardType: "coin", RewardCoins: 100, RTPValueCoins: 100, WeightPPM: 1, Enabled: true},
		},
	})
	if config.Tiers[0].RTPValueCoins != 0 || config.Tiers[1].RTPValueCoins != 0 {
		t.Fatalf("prop and dress rtp values must be zero: %#v", config.Tiers)
	}
	if config.Tiers[2].RTPValueCoins != 100 {
		t.Fatalf("coin rtp value should be preserved: %#v", config.Tiers[2])
	}
}

func TestValidateRuleConfigRejectsPropRTPValueAfterNormalizationByCallerMutation(t *testing.T) {
	config := NormalizeRuleConfig(domain.RuleConfig{
		WheelID:               "custom",
		DrawPriceCoins:        100,
		SettlementWindowDraws: 1000,
		Tiers: []domain.Tier{
			{TierID: "prop", RewardType: "prop", RewardID: "car_1", WeightPPM: 1, Enabled: true},
		},
	})
	config.Tiers[0].RTPValueCoins = 100
	if err := ValidateRuleConfig(config); err != nil {
		t.Fatalf("ValidateRuleConfig should normalize prop rtp value before validation: %v", err)
	}
}

func TestValidateRuleConfigRejectsClassicNineTiers(t *testing.T) {
	tiers := make([]domain.Tier, 0, 9)
	for index := 0; index < 9; index++ {
		tiers = append(tiers, domain.Tier{
			TierID:      fmt.Sprintf("classic-%d", index+1),
			RewardType:  "coin",
			RewardCoins: 100,
			WeightPPM:   1,
			Enabled:     true,
		})
	}
	err := ValidateRuleConfig(domain.RuleConfig{
		WheelID:               "classic",
		DrawPriceCoins:        100,
		SettlementWindowDraws: 1000,
		Tiers:                 tiers,
	})
	if err == nil || !strings.Contains(err.Error(), "requires 8 tiers") {
		t.Fatalf("classic should reject nine tiers, got %v", err)
	}
}
