package scheduler

import (
	"testing"
	"time"

	"github.com/nomadcode/nomadcode-core/internal/workflow"
)

func TestIsAuthoringStaleReturnsTrueWhenExpired(t *testing.T) {
	old := time.Now().Add(-2000 * time.Second)
	if !IsAuthoringStale(old, 1200) {
		t.Fatal("expected stale for timestamp older than threshold")
	}
}

func TestIsAuthoringStaleReturnsFalseWhenRecent(t *testing.T) {
	recent := time.Now().Add(-60 * time.Second)
	if IsAuthoringStale(recent, 1200) {
		t.Fatal("expected not stale for recent timestamp")
	}
}

func TestIsAuthoringStaleReturnsFalseForZeroTime(t *testing.T) {
	if IsAuthoringStale(time.Time{}, 1200) {
		t.Fatal("expected false for zero time")
	}
}

func TestIsAuthoringStaleReturnsFalseForNonPositiveThreshold(t *testing.T) {
	old := time.Now().Add(-9999 * time.Second)
	if IsAuthoringStale(old, 0) {
		t.Fatal("expected false when threshold is zero (feature disabled)")
	}
	if IsAuthoringStale(old, -1) {
		t.Fatal("expected false when threshold is negative")
	}
}

func TestParseAuthoringRunUpdatedAtReturnsTimeFromMeta(t *testing.T) {
	now := time.Now().UTC().Truncate(time.Second)
	meta := map[string]any{
		workflow.MetadataKeyAuthoringRunUpdatedAt: now.Format(time.RFC3339),
	}
	got := ParseAuthoringRunUpdatedAt(meta)
	if !got.Equal(now) {
		t.Fatalf("got %v, want %v", got, now)
	}
}

func TestParseAuthoringRunUpdatedAtReturnsZeroOnMissing(t *testing.T) {
	if !ParseAuthoringRunUpdatedAt(map[string]any{}).IsZero() {
		t.Fatal("expected zero time when key is absent")
	}
}

func TestParseAuthoringRunUpdatedAtReturnsZeroOnBadFormat(t *testing.T) {
	meta := map[string]any{
		workflow.MetadataKeyAuthoringRunUpdatedAt: "not-a-date",
	}
	if !ParseAuthoringRunUpdatedAt(meta).IsZero() {
		t.Fatal("expected zero time for unparseable date")
	}
}

// TestIsAuthoringStaleAppliesToQueueWait verifies that the stale helper can be
// applied to task.UpdatedAt for queue-waiting authoring tasks: if a task has
// been queued for longer than AUTHORING_STALE_AFTER_SEC it is considered stale.
func TestIsAuthoringStaleAppliesToQueueWait(t *testing.T) {
	// Simulate a task queued 25 minutes ago (threshold default 1200s = 20min).
	queuedAt := time.Now().Add(-25 * time.Minute)
	if !IsAuthoringStale(queuedAt, 1200) {
		t.Fatal("expected stale for task queued longer than threshold")
	}

	// A task queued 10 minutes ago is not yet stale.
	recent := time.Now().Add(-10 * time.Minute)
	if IsAuthoringStale(recent, 1200) {
		t.Fatal("expected not stale for task queued less than threshold")
	}
}
