package transfer

import (
	"context"
	"log/slog"
	"time"
)

// PendingTTL is the wall-clock window after which a PENDING session
// is auto-cancelled by the sweeper (plan §4.5 待决策清单 #5).
const PendingTTL = 120 * time.Second

// SweepInterval is how often the sweeper goroutine wakes up.
const SweepInterval = 30 * time.Second

// RunSweeper blocks until ctx is cancelled, periodically expiring
// stale PENDING sessions.
func RunSweeper(ctx context.Context, svc *Service) {
	t := time.NewTicker(SweepInterval)
	defer t.Stop()
	for {
		select {
		case <-ctx.Done():
			return
		case <-t.C:
			n, err := svc.ExpirePending(ctx, PendingTTL)
			if err != nil {
				slog.Error("sweeper: expire pending failed", "err", err)
				continue
			}
			if n > 0 {
				slog.Info("sweeper: expired pending sessions", "count", n)
			}
		}
	}
}
