package healthcheck

import (
	"time"

	"github.com/pingcap/log"
	"github.com/robfig/cron/v3"
	"go.uber.org/zap"
)

// cronParser is the global cron parser instance
// Supports standard 5-field cron: minute hour dom month dow
// Also supports descriptors like "@hourly", "@daily", etc.
var cronParser = cron.NewParser(cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow | cron.Descriptor)

// calculateNextRunTime calculates the next run time based on the cron expression
// Returns nil if the expression is invalid or empty
func calculateNextRunTime(cronExpr string, fromTime ...time.Time) *time.Time {
	if cronExpr == "" {
		return nil
	}

	schedule, err := cronParser.Parse(cronExpr)
	if err != nil {
		log.Error("failed to parse cron expression",
			zap.String("expression", cronExpr),
			zap.Error(err),
		)
		return nil
	}

	baseTime := time.Now()
	if len(fromTime) > 0 {
		baseTime = fromTime[0]
	}

	next := schedule.Next(baseTime)
	return &next
}

// validateCronExpression validates if the given string is a valid cron expression
func validateCronExpression(cronExpr string) error {
	if cronExpr == "" {
		return nil
	}
	_, err := cronParser.Parse(cronExpr)
	return err
}

// getCronSchedule returns the cron.Schedule for the given expression
// This can be used to get more information about the schedule
func getCronSchedule(cronExpr string) (cron.Schedule, error) {
	return cronParser.Parse(cronExpr)
}
