package agent

import (
	"context"
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
	"go.uber.org/mock/gomock"
	"k8s.io/apimachinery/pkg/util/wait"
)

func TestRun(t *testing.T) {
	ctrl := gomock.NewController(t)
	ctx, cancel := context.WithCancel(context.Background())

	var scanHasRun bool
	schedule := NewMockSchedule(ctrl)
	schedule.EXPECT().Next(gomock.Any()).
		AnyTimes().
		DoAndReturn(func(t time.Time) time.Time {
			if !scanHasRun {
				scanHasRun = true
				return t // run now
			}

			// After the first run, never run again (effectively)
			return t.Add(1000 * time.Hour)
		})

	var success bool
	job := &TestJob{
		RunFunc: func() {
			success = true
			cancel()
		},
	}

	w := &schedulerWorker{
		job:     job,
		cadence: schedule,
	}

	var wg wait.Group
	wg.StartWithContext(ctx, w.Run)
	wg.Wait()

	assert.True(t, success, "Calls the job's runFunc and cancels")
}
