// go-server/internal/license/clock.go
package license

import (
	"sync"
	"time"
)

// clockSkewTolerance is used in Manager to allow 5min of NTP drift when
// detecting clock rollbacks at startup.
const clockSkewTolerance = 5 * time.Minute

// HighWaterClock is a monotonically advancing clock. Its mark never decreases.
// Bootstrap it from the persisted HighWaterMark on startup. Concurrency-safe.
type HighWaterClock struct {
	mu   sync.Mutex
	mark time.Time
}

// Bootstrap advances the mark to persisted if it is later than the current mark.
func (c *HighWaterClock) Bootstrap(persisted time.Time) {
	if persisted.IsZero() {
		return
	}
	c.mu.Lock()
	defer c.mu.Unlock()
	if persisted.After(c.mark) {
		c.mark = persisted
	}
}

// Now returns max(time.Now(), mark) and advances the mark.
func (c *HighWaterClock) Now() time.Time {
	c.mu.Lock()
	defer c.mu.Unlock()
	now := time.Now()
	if now.After(c.mark) {
		c.mark = now
		return now
	}
	return c.mark
}

// Observe advances the mark to serverTime if it is later.
// Call this with the IssuedAt from a signed heartbeat response.
func (c *HighWaterClock) Observe(serverTime time.Time) {
	if serverTime.IsZero() {
		return
	}
	c.mu.Lock()
	defer c.mu.Unlock()
	if serverTime.After(c.mark) {
		c.mark = serverTime
	}
}
