package schedulers

import (
	"context"

	"testing"
	"time"

	commM "github.com/pingcap/test-infra/common/model"
	"github.com/pingcap/test-infra/common/model/tcms/taskruns"
	"github.com/pingcap/test-infra/services/tps/pkg/common"
	"github.com/stretchr/testify/assert"
)

func newRetrialJob(cnt int, startAt time.Time) *common.ArgoJob {
	var st = commM.Timestamp(startAt.Unix())
	return &common.ArgoJob{
		PlanExec:     &commM.TestPlanExecution{RetryCnt: cnt, Status: commM.ExecutionStatusPrepareBackoff, StartedAt: &st},
		TestbedSetup: &taskruns.TestbedSetup{Status: taskruns.TestbedSetupStatus{Schedule: &taskruns.Schedule{}}},
	}
}

func TestFilter(t *testing.T) {
	now := time.Unix(0, 0).Add(2 * MaxWaitTime)
	s := &Backoff{now: func() time.Time {
		return now
	}}
	jobs := []*common.ArgoJob{
		newRetrialJob(1, now.Add(-MinWaitTime-genRandomSeconds(newRetrialJob(1, now))-time.Second)),
		newRetrialJob(2, now.Add(-MinWaitTime-genRandomSeconds(newRetrialJob(2, now))-time.Second)),
		{PlanExec: &commM.TestPlanExecution{Status: commM.ExecutionStatusPending}},
		newRetrialJob(100, now.Add(-MaxWaitTime-genRandomSeconds(newRetrialJob(100, now))-time.Second)),
	}
	expected := []*common.ArgoJob{jobs[0], jobs[2], jobs[3]}
	rt, err := s.Filter(context.TODO(), jobs)
	assert.NoError(t, err)
	assert.Equal(t, expected, rt)
}
