package cron

import (
	"fmt"
	"time"

	"haixun-backend/internal/library/clock"

	"github.com/robfig/cron/v3"
)

func NextRunAt(cronExpr, timezone string, from time.Time) (int64, error) {
	expr := cronExpr
	parser := cron.NewParser(cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow)
	schedule, err := parser.Parse(expr)
	if err != nil {
		return 0, fmt.Errorf("invalid cron expression: %w", err)
	}

	loc := time.UTC
	if timezone != "" {
		loaded, loadErr := time.LoadLocation(timezone)
		if loadErr != nil {
			return 0, fmt.Errorf("invalid timezone: %w", loadErr)
		}
		loc = loaded
	}

	next := schedule.Next(from.In(loc))
	return clock.UnixNano(next), nil
}
