package core

import (
	"testing"
	"time"
)

func TestNextCronTime(t *testing.T) {
	utc := time.UTC

	t.Run("0 * * * * desde :30 retorna la proxima hora en punto", func(t *testing.T) {
		sched, err := ParseCronExpr("0 * * * *")
		if err != nil {
			t.Fatalf("unexpected error: %v", err)
		}
		after := time.Date(2024, 1, 15, 14, 30, 0, 0, utc)
		got := NextCronTime(sched, after)
		want := time.Date(2024, 1, 15, 15, 0, 0, 0, utc)
		if !got.Equal(want) {
			t.Errorf("got %v, want %v", got, want)
		}
	})

	t.Run("@weekly desde viernes retorna proximo domingo a medianoche", func(t *testing.T) {
		// @weekly = "0 0 * * 0" (Sunday)
		sched, err := ParseCronExpr("@weekly")
		if err != nil {
			t.Fatalf("unexpected error: %v", err)
		}
		// 2024-01-19 is a Friday
		after := time.Date(2024, 1, 19, 10, 0, 0, 0, utc)
		got := NextCronTime(sched, after)
		// Next Sunday = 2024-01-21
		want := time.Date(2024, 1, 21, 0, 0, 0, 0, utc)
		if !got.Equal(want) {
			t.Errorf("got %v, want %v", got, want)
		}
	})

	t.Run("0 9 * * 1-5 desde viernes retorna proximo lunes a las 9", func(t *testing.T) {
		sched, err := ParseCronExpr("0 9 * * 1-5")
		if err != nil {
			t.Fatalf("unexpected error: %v", err)
		}
		// 2024-01-19 is a Friday, after 9am so today is already past.
		after := time.Date(2024, 1, 19, 10, 0, 0, 0, utc)
		got := NextCronTime(sched, after)
		// Next weekday = Monday 2024-01-22
		want := time.Date(2024, 1, 22, 9, 0, 0, 0, utc)
		if !got.Equal(want) {
			t.Errorf("got %v, want %v", got, want)
		}
	})

	t.Run("schedule imposible retorna zero time", func(t *testing.T) {
		// 30 Feb does not exist — will exhaust 366-day limit quickly for a specific year.
		// Use a schedule matching only Feb 30, which never occurs.
		sched := CronSchedule{
			Minute:     []int{0},
			Hour:       []int{0},
			DayOfMonth: []int{30},
			Month:      []int{2},
			DayOfWeek:  []int{0, 1, 2, 3, 4, 5, 6},
			Raw:        "0 0 30 2 *",
		}
		after := time.Date(2023, 3, 1, 0, 0, 0, 0, utc)
		got := NextCronTime(sched, after)
		if !got.IsZero() {
			t.Errorf("expected zero time for impossible schedule, got %v", got)
		}
	})
}
