package server

import (
	"testing"
	"time"
)

// TestLazySweepSubSecondThrottle guards the sub-second lazy-sweep throttle:
// truncating a 500ms interval to whole seconds would make it 0 and allow every
// write to launch a retention sweep. Repeated writes inside the interval must
// stay throttled, and the slot must be claimed again only after the interval.
func TestLazySweepSubSecondThrottle(t *testing.T) {
	s := NewWithConfig(Config{FSEventsLazySweepInterval: 500 * time.Millisecond})
	bus := &EventBus{}
	base := time.Now().UnixNano()

	if !s.lazySweepDue(bus, base) {
		t.Fatal("first write should claim the sweep slot")
	}
	if s.lazySweepDue(bus, base+int64(100*time.Millisecond)) {
		t.Fatal("write inside the 500ms interval must be throttled")
	}
	if got := bus.lastSweepUnixNano.Load(); got != base {
		t.Fatalf("throttled write must not move the sweep timestamp: got %d, want %d", got, base)
	}
	if !s.lazySweepDue(bus, base+int64(600*time.Millisecond)) {
		t.Fatal("write after the 500ms interval should claim the sweep slot again")
	}
	if got := bus.lastSweepUnixNano.Load(); got != base+int64(600*time.Millisecond) {
		t.Fatalf("claimed sweep timestamp = %d, want %d", got, base+int64(600*time.Millisecond))
	}
}
