package sink

import (
	"testing"
	"time"
)

func TestRandDurationWeirdValues(t *testing.T) {
	// Shouldn't panic on min == max
	_ = randDuration(1, 1)
	// Shouldn't panic on min > max
	_ = randDuration(10, 0)
	// shouldn't panic on min=max+1
	_ = randDuration(0, 1)
}

func TestBackoffZero(t *testing.T) {
	// First backoff should give zero.
	have := backoff(0, time.Second, 5*time.Second)
	want := time.Duration(0)
	if have != want {
		t.Errorf("backoff(0, time.Second, 5*time.Second) have=%s want=%s", have, want)
	}
}

func TestBackoffVeryLargeRetryCount(t *testing.T) {
	// Shouldn't panic when the retry count is very large.
	have := backoff(1e6, time.Second, 5*time.Second)
	want := 5 * time.Second
	if !withinJitter(have, want, jitter) {
		t.Errorf("backoff(0, time.Second, 5*time.Second) have=%s want=%s", have, want)
	}
}

func withinJitter(have, want time.Duration, jitter float64) bool {
	var delta time.Duration
	if have < want {
		delta = want - have
	} else {
		delta = have - want
	}
	tolerance := time.Duration(jitter * float64(want))
	return delta < tolerance
}
