package cron

import (
	"testing"
	"time"
)

func TestJobFiresAtExpectedTime(t *testing.T) {
	fired := make(chan struct{}, 1)

	job := func() {
		select {
		case fired <- struct{}{}:
		default:
		}
	}

	// Every second (6 fields because cron is created with WithSeconds).
	scheduler, err := NewCronScheduler("* * * * * *", job)
	if err != nil {
		t.Fatalf("NewCronScheduler failed: %v", err)
	}

	scheduler.Start()

	select {
	case <-fired:
		// Job fired as expected.
	case <-time.After(3 * time.Second):
		t.Fatal("job did not fire within expected time")
	}

	stoppedCtx := scheduler.Stop()
	select {
	case <-stoppedCtx.Done():
		// Scheduler stopped cleanly.
	case <-time.After(2 * time.Second):
		t.Fatal("scheduler did not stop within expected time")
	}
}

func TestStopReturnsContext(t *testing.T) {
	scheduler, err := NewCronScheduler("* * * * * *", func() {})
	if err != nil {
		t.Fatalf("NewCronScheduler failed: %v", err)
	}

	scheduler.Start()

	stoppedCtx := scheduler.Stop()
	if stoppedCtx == nil {
		t.Fatal("Stop returned nil context")
	}

	select {
	case <-stoppedCtx.Done():
		// Expected.
	case <-time.After(2 * time.Second):
		t.Fatal("stopped context was not cancelled")
	}
}
