package cache

import (
	"sync"
	"time"
)

type entry struct {
	data      []byte
	expiresAt time.Time
}

type Cache struct {
	mu      sync.RWMutex
	entries map[string]*entry
	ttl     time.Duration
	// maxEntries > 0 caps the entries held (see NewWithLimit); 0 is no cap.
	maxEntries int
}

func New(ttl time.Duration) *Cache {
	return NewWithLimit(ttl, 0)
}

// NewWithLimit is New holding at most maxEntries entries: once full, Set
// drops the expired ones and, if it is still full, doesn't add a new key.
// For caches keyed by request input (e.g. any search query), so their size
// stays bounded.
func NewWithLimit(ttl time.Duration, maxEntries int) *Cache {
	c := &Cache{
		entries:    make(map[string]*entry),
		ttl:        ttl,
		maxEntries: maxEntries,
	}
	go c.janitor()
	return c
}

func (c *Cache) Get(key string) ([]byte, bool) {
	c.mu.RLock()
	defer c.mu.RUnlock()

	e, exists := c.entries[key]
	if !exists {
		return nil, false
	}

	if time.Now().After(e.expiresAt) {
		return nil, false
	}

	return e.data, true
}

func (c *Cache) Set(key string, data []byte) {
	c.mu.Lock()
	defer c.mu.Unlock()

	if _, exists := c.entries[key]; !exists && c.maxEntries > 0 && len(c.entries) >= c.maxEntries {
		c.deleteExpired(time.Now())
		if len(c.entries) >= c.maxEntries {
			return
		}
	}
	c.entries[key] = &entry{
		data:      data,
		expiresAt: time.Now().Add(c.ttl),
	}
}

func (c *Cache) janitor() {
	ticker := time.NewTicker(5 * time.Minute)
	defer ticker.Stop()

	for range ticker.C {
		c.mu.Lock()
		c.deleteExpired(time.Now())
		c.mu.Unlock()
	}
}

// deleteExpired drops the entries expired at now. The caller holds c.mu.
func (c *Cache) deleteExpired(now time.Time) {
	for key, e := range c.entries {
		if now.After(e.expiresAt) {
			delete(c.entries, key)
		}
	}
}
