package memory

import (
	"sync"
	"time"

	"github.com/google/uuid"
)

const (
	// SignatureCacheTTL is the time-to-live for cached signatures (24 hours)
	SignatureCacheTTL = 24 * time.Hour
)

// signatureCacheEntry represents a cached signature with expiration
type signatureCacheEntry struct {
	Signature []byte
	ExpiresAt time.Time
}

// SignatureCache provides in-memory caching for signatures
type SignatureCache struct {
	cache sync.Map
}

// Global signature cache instance
var globalSignatureCache = &SignatureCache{}

// GetSignatureCache returns the global signature cache instance
func GetSignatureCache() *SignatureCache {
	return globalSignatureCache
}

// Set stores a signature in the cache with 24h TTL
func (c *SignatureCache) Set(sessionID uuid.UUID, signature []byte) {
	entry := signatureCacheEntry{
		Signature: signature,
		ExpiresAt: time.Now().Add(SignatureCacheTTL),
	}
	c.cache.Store(sessionID.String(), entry)
}

// Get retrieves a signature from the cache
func (c *SignatureCache) Get(sessionID uuid.UUID) ([]byte, bool) {
	value, ok := c.cache.Load(sessionID.String())
	if !ok {
		return nil, false
	}

	entry := value.(signatureCacheEntry)

	// Check if expired
	if time.Now().After(entry.ExpiresAt) {
		c.cache.Delete(sessionID.String())
		return nil, false
	}

	return entry.Signature, true
}
