package service

import (
	"math/rand"
	"testing"
	"time"

	roomv1 "hyapp.local/api/proto/room/v1"
	"hyapp/pkg/xerr"
)

func TestHumanRoomRobotGiftSenderLimit(t *testing.T) {
	activity := newRobotRoomActivity([]int64{101, 102, 103, 104})
	for _, userID := range []int64{101, 102, 103, 104} {
		activity.markActive(userID)
	}

	markInitialHumanRoomGiftSenders(activity, []int64{101, 102, 103, 104}, 2)
	if got := activity.giftSenderCount(); got != 2 {
		t.Fatalf("gift sender count mismatch: got %d want 2", got)
	}
	if activity.markGiftSenderWithinLimit(104, 2) {
		t.Fatalf("gift sender limit allowed one more sender")
	}
}

func TestHumanRoomRobotGiftPresenceDriftRemovesStaleUsers(t *testing.T) {
	activity := newRobotRoomActivity([]int64{101, 102, 103})
	for _, userID := range []int64{101, 102, 103} {
		activity.markActive(userID)
	}
	activity.markGiftSender(101)

	reconcileHumanRoomRobotGiftPresence(activity, 101, 102, xerr.New(xerr.NotFound, "sender not in room"))
	if activity.isActive(101) || activity.isGiftSender(101) {
		t.Fatalf("stale sender must be removed from active and gift sender sets")
	}
	if !activity.isActive(102) {
		t.Fatalf("target must stay active when sender is stale")
	}

	activity.markActive(101)
	activity.markGiftSender(101)
	reconcileHumanRoomRobotGiftPresence(activity, 101, 102, xerr.New(xerr.NotFound, "target not in room"))
	if !activity.isActive(101) || !activity.isGiftSender(101) {
		t.Fatalf("sender must stay active when target is stale")
	}
	if activity.isActive(102) {
		t.Fatalf("stale target must be removed from active set")
	}
}

func TestHumanRoomRobotNormalGiftDelayRange(t *testing.T) {
	rng := rand.New(rand.NewSource(1))
	config := HumanRoomRobotConfig{NormalGiftIntervalMinMS: 1000, NormalGiftIntervalMaxMS: 20000}
	for i := 0; i < 100; i++ {
		delay := humanRoomRobotNormalGiftDelay(config, rng)
		if delay < time.Second || delay > 20*time.Second {
			t.Fatalf("gift delay out of range: %s", delay)
		}
	}
}

func TestRandomHumanRoomTargetOnlineRange(t *testing.T) {
	config := HumanRoomRobotConfig{RoomTargetMinOnline: 8, RoomTargetMaxOnline: 10}
	for i := 0; i < 100; i++ {
		target := randomHumanRoomTargetOnline(config)
		if target < 8 || target > 10 {
			t.Fatalf("target online out of range: %d", target)
		}
	}
}

func TestRandomHumanRoomTargetOnlineLegacyFixedValue(t *testing.T) {
	config := HumanRoomRobotConfig{RoomFullStopOnline: 10}
	for i := 0; i < 20; i++ {
		if target := randomHumanRoomTargetOnline(config); target != 10 {
			t.Fatalf("legacy target online mismatch: got %d want 10", target)
		}
	}
}

func TestNormalizeHumanRoomRobotCountryRules(t *testing.T) {
	rules, err := normalizeHumanRoomRobotCountryRules([]*roomv1.AdminHumanRoomRobotCountryRule{
		{CountryCode: "sa", MaxRoomCount: 2, AllowedOwnerIds: []string{" 1001 ", "1001", "1002"}},
		{CountryCode: "AE", MaxRoomCount: 1},
	})
	if err != nil {
		t.Fatalf("normalize country rules failed: %v", err)
	}
	if len(rules) != 2 || rules[0].CountryCode != "AE" || rules[1].CountryCode != "SA" || rules[1].MaxRoomCount != 2 {
		t.Fatalf("country rules mismatch: %+v", rules)
	}
	if len(rules[1].AllowedOwnerIDs) != 2 || rules[1].AllowedOwnerIDs[0] != "1001" || rules[1].AllowedOwnerIDs[1] != "1002" {
		t.Fatalf("country rule allowed owners mismatch: %+v", rules[1].AllowedOwnerIDs)
	}
	limits := humanRoomRobotCountryLimits(HumanRoomRobotConfig{CountryLimitEnabled: true, CountryRules: rules})
	if limits["SA"] != 2 || limits["AE"] != 1 || len(limits) != 2 {
		t.Fatalf("country limits mismatch: %+v", limits)
	}
}

func TestHumanRoomRobotAllowedOwnersForCountryPrefersCountryRule(t *testing.T) {
	config := HumanRoomRobotConfig{
		AllowedOwnerIDs: []string{"global-owner"},
		CountryRules: []HumanRoomRobotCountryRule{
			{CountryCode: "SA", MaxRoomCount: 2, AllowedOwnerIDs: []string{"sa-owner"}},
			{CountryCode: "AE", MaxRoomCount: 1},
		},
	}
	if got := humanRoomRobotAllowedOwnersForCountry(config, "sa"); len(got) != 1 || got[0] != "sa-owner" {
		t.Fatalf("country rule allowed owners should win, got %+v", got)
	}
	if got := humanRoomRobotAllowedOwnersForCountry(config, "AE"); len(got) != 1 || got[0] != "global-owner" {
		t.Fatalf("empty country rule should fall back to global owners, got %+v", got)
	}
	if got := humanRoomRobotAllowedOwnersForCountry(config, "KW"); len(got) != 1 || got[0] != "global-owner" {
		t.Fatalf("missing country rule should fall back to global owners, got %+v", got)
	}
}

func TestNormalizeHumanRoomRobotCountryRulesRejectsDuplicate(t *testing.T) {
	if _, err := normalizeHumanRoomRobotCountryRules([]*roomv1.AdminHumanRoomRobotCountryRule{
		{CountryCode: "SA", MaxRoomCount: 2},
		{CountryCode: "sa", MaxRoomCount: 3},
	}); err == nil {
		t.Fatalf("duplicated country rules must be rejected")
	}
}
