package agentd

import (
	"context"
	"time"
)

// runTTL periodically sweeps expired credentials out of the local table. It runs
// for the whole agent lifetime (independent of the control-plane connection) so
// credentials expire on time even during a network partition.
//
// Per doc/06, sing-box has no native per-user TTL: free-plan credentials carry the
// current day's remaining minutes as expires_at, and paid (24h) credentials are
// refreshed by RotateCredential/Upsert commands from the control plane. When a
// credential expires the agent removes it locally, re-renders sing-box and (via
// SingBox.OnExpire) surfaces the removal upstream.
func (a *Agent) runTTL(ctx context.Context) {
	ticker := time.NewTicker(a.cfg.TTLScanInterval)
	defer ticker.Stop()
	for {
		select {
		case <-ctx.Done():
			return
		case <-ticker.C:
			if removed := a.sb.sweepExpired(); len(removed) > 0 {
				logf("ttl sweep removed %d expired credential(s)", len(removed))
			}
		}
	}
}
