package jwtauth

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

	"commilitia.net/cdrop/internal/db"
)

// DeviceSweepInterval is how often the device sweeper wakes up.
const DeviceSweepInterval = 1 * time.Hour

// RunDeviceSweeper prunes the devices table on a timer: it drops devices whose
// last_seen is older than ttl, so a registration never outlives the broker session's
// refresh window (a device idle past the window has no live broker session anyway).
// The session is the broker's source of truth; this only reaps stale local rows. ttl
// ≤ 0 disables the sweeper.
func RunDeviceSweeper(ctx context.Context, queries *db.Queries, ttl time.Duration) {
	if ttl <= 0 {
		slog.Info("device sweeper disabled (ttl <= 0)")
		return
	}
	slog.Info("device sweeper running", "ttl", ttl, "interval", DeviceSweepInterval)

	t := time.NewTicker(DeviceSweepInterval)
	defer t.Stop()
	for {
		select {
		case <-ctx.Done():
			return
		case <-t.C:
			cutoff := time.Now().Add(-ttl).Unix()
			if err := queries.DeleteStaleDevices(ctx, cutoff); err != nil {
				slog.Error("device sweeper failed", "err", err)
			}
		}
	}
}
