package job

import (
	"context"
	"log"
	"time"

	domusecase "haixun-backend/internal/model/job/domain/usecase"
)

type Scheduler struct {
	holder string
	jobs   domusecase.UseCase
}

func NewScheduler(holder string, jobs domusecase.UseCase) *Scheduler {
	return &Scheduler{holder: holder, jobs: jobs}
}

func (s *Scheduler) Start(ctx context.Context, interval time.Duration) {
	if interval <= 0 {
		interval = time.Minute
	}
	log.Printf("job scheduler started: holder=%s interval=%s", s.holder, interval)
	ticker := time.NewTicker(interval)
	defer ticker.Stop()

	for {
		select {
		case <-ctx.Done():
			log.Printf("job scheduler stopped: holder=%s", s.holder)
			return
		case <-ticker.C:
			created, err := s.jobs.RunSchedulerTick(ctx, s.holder)
			if err != nil {
				log.Printf("job scheduler tick error: %v", err)
				continue
			}
			if created > 0 {
				log.Printf("job scheduler created %d run(s)", created)
			}
		}
	}
}
