package job

import (
	"context"
	"log"
	"time"

	publishqueuedomain "haixun-backend/internal/model/publish_queue/domain/usecase"
)

type PublishQueueSweeper struct {
	queue     publishqueuedomain.UseCase
	batchSize int
}

func NewPublishQueueSweeper(queue publishqueuedomain.UseCase, batchSize int) *PublishQueueSweeper {
	if batchSize <= 0 {
		batchSize = 20
	}
	return &PublishQueueSweeper{queue: queue, batchSize: batchSize}
}

func (s *PublishQueueSweeper) Start(ctx context.Context, interval time.Duration) {
	if s == nil || s.queue == nil {
		return
	}
	if interval <= 0 {
		interval = time.Minute
	}
	log.Printf("publish queue sweeper started: interval=%s batch=%d", interval, s.batchSize)
	ticker := time.NewTicker(interval)
	defer ticker.Stop()

	for {
		select {
		case <-ctx.Done():
			log.Printf("publish queue sweeper stopped")
			return
		case <-ticker.C:
			missed, err := s.queue.MarkMissed(ctx, int64(10*time.Minute), s.batchSize)
			if err != nil {
				log.Printf("publish queue missed sweep error: %v", err)
			} else if missed > 0 {
				log.Printf("publish queue marked %d missed item(s)", missed)
			}
			dispatched, err := s.queue.DispatchDue(ctx, s.batchSize)
			if err != nil {
				log.Printf("publish queue sweeper tick error: %v", err)
				continue
			}
			if dispatched > 0 {
				log.Printf("publish queue sweeper dispatched %d item(s)", dispatched)
			}
		}
	}
}
