package worker

import (
	"testing"
	"time"

	"code.justin.tv/live/autohost/internal/worker/clock"
	"github.com/stretchr/testify/require"
)

// Verify that requireWithinThreshold allows calls when the number of live channels is not more than 10%
// smaller than the previous value.
func TestLiveChannelCheckWithinThreshold(t *testing.T) {
	testClock := clock.NewTestClock()
	testClock.Set(time.Now())
	c := newLiveChannelCheck(testClock)

	err := c.requireWithinThreshold(100_000)
	require.NoError(t, err)

	testClock.Add(15 * time.Second)
	err = c.requireWithinThreshold(90_000)
	require.NoError(t, err)
}

// Verify that requireWithinThreshold returns an error when the number of live channels is more than 10%
// smaller than the previous value.
func TestLiveChannelCheckLessThanThreshold(t *testing.T) {
	testClock := clock.NewTestClock()
	testClock.Set(time.Now())
	c := newLiveChannelCheck(testClock)

	err := c.requireWithinThreshold(100_000)
	require.NoError(t, err)

	testClock.Add(15 * time.Second)
	err = c.requireWithinThreshold(89_999)
	require.Error(t, err)
}

// Verify that requireWithinThreshold allows calls if the previous value hasn't been updated in 2 minutes.
func TestLiveChannelCheckResetThreshold(t *testing.T) {
	testClock := clock.NewTestClock()
	testClock.Set(time.Now())
	c := newLiveChannelCheck(testClock)

	err := c.requireWithinThreshold(100_000)
	require.NoError(t, err)

	testClock.Add(2*time.Minute + time.Second)
	err = c.requireWithinThreshold(89_999)
	require.NoError(t, err)
}

// Verify that requireWithinThreshold allows calls when the number of live channels is greater than
// the previous value.
func TestLiveChannelCheckLargeIncrease(t *testing.T) {
	testClock := clock.NewTestClock()
	testClock.Set(time.Now())
	c := newLiveChannelCheck(testClock)

	err := c.requireWithinThreshold(100_000)
	require.NoError(t, err)

	testClock.Add(15 * time.Second)
	err = c.requireWithinThreshold(200_000)
	require.NoError(t, err)
}
