package delivery

import (
	"testing"
	"time"

	"github.com/stretchr/testify/require"

	"github.com/tidbcloud/alertstore/pkg/alert"
)

func TestEscalationStartDelayIsZeroForARuleThatAsksForNothing(t *testing.T) {
	t.Parallel()

	now := time.Now()
	a := &alert.Alert{CreatedAt: now.Add(-time.Second)}

	require.Zero(t, escalationStartDelay(a, &alert.AlertAttrs{}, now))
}

func TestEscalationStartDelayCountsWhatThePipelineAlreadySpent(t *testing.T) {
	t.Parallel()

	// The window belongs to the condition, not to the delivery pipeline. A rule
	// asking for five minutes gets five minutes from the alert, so the two
	// minutes ingest and the oncall lookup took come out of it — not on top.
	now := time.Now()
	a := &alert.Alert{CreatedAt: now.Add(-2 * time.Minute)}
	attrs := &alert.AlertAttrs{Annotations: map[string]string{alert.PageDelayAnnotation: "5m"}}

	require.Equal(t, 3*time.Minute, escalationStartDelay(a, attrs, now))
}

func TestEscalationStartDelayPagesNowWhenTheWindowIsAlreadyGone(t *testing.T) {
	t.Parallel()

	// A pipeline slower than the window it was asked to respect does not owe
	// anyone more waiting. The caller treats a non-positive delay as "enqueue
	// immediately", so a stalled worker catching up pages rather than schedules
	// a call into the past.
	now := time.Now()
	a := &alert.Alert{CreatedAt: now.Add(-30 * time.Minute)}
	attrs := &alert.AlertAttrs{Annotations: map[string]string{alert.PageDelayAnnotation: "5m"}}

	require.LessOrEqual(t, escalationStartDelay(a, attrs, now), time.Duration(0))
}
