package services

import (
	"sync"
	"time"
)

type SettingsCache struct {
	data       map[string]string
	mu         sync.RWMutex
	ttl        time.Duration
	lastUpdate time.Time
}

func NewSettingsCache(ttl time.Duration) *SettingsCache {
	return &SettingsCache{
		data:       make(map[string]string),
		ttl:        ttl,
		lastUpdate: time.Now(),
	}
}

func (c *SettingsCache) Get(key string) (string, bool) {
	c.mu.RLock()
	defer c.mu.RUnlock()

	// Check if cache is expired
	if time.Since(c.lastUpdate) > c.ttl {
		return "", false
	}

	val, ok := c.data[key]
	return val, ok
}

func (c *SettingsCache) Set(key, value string) {
	c.mu.Lock()
	defer c.mu.Unlock()

	c.data[key] = value
	c.lastUpdate = time.Now()
}

func (c *SettingsCache) Invalidate() {
	c.mu.Lock()
	defer c.mu.Unlock()

	c.data = make(map[string]string)
	c.lastUpdate = time.Time{}
}

func (c *SettingsCache) InvalidateKey(key string) {
	c.mu.Lock()
	defer c.mu.Unlock()

	delete(c.data, key)
}
