package replay

import (
	"sync"
	"time"
)

type MemoryStore struct {
	mu   sync.Mutex
	seen map[string]int64 // key -> expiry unix ms
}

func NewMemoryStore() *MemoryStore {
	return &MemoryStore{seen: make(map[string]int64)}
}

// SeenBefore returns true if key already exists and not expired.
// It also inserts/refreshes the key with given expiry.
func (s *MemoryStore) SeenBefore(key string, expiryMs int64) bool {
	nowMs := time.Now().UnixMilli()

	s.mu.Lock()
	defer s.mu.Unlock()

	// opportunistic cleanup
	for k, exp := range s.seen {
		if exp <= nowMs {
			delete(s.seen, k)
		}
	}

	if exp, ok := s.seen[key]; ok {
		if exp > nowMs {
			return true
		}
	}
	s.seen[key] = expiryMs
	return false
}
