package queries

import (
	"bssapp-backend/models"
	"database/sql"
	"sync"
	"time"
)

/* ===============================
   CACHE STRUCT
================================ */

type currencyCacheItem struct {
	data      *models.TodayCurrencyV3
	expiresAt time.Time
}

var (
	currencyCache = make(map[string]currencyCacheItem)
	cacheMutex    sync.RWMutex
	cacheTTL      = 5 * time.Minute
)

/* ===============================
   MAIN CACHE FUNC
================================ */

func GetCachedCurrencyV3(db *sql.DB, code string) (*models.TodayCurrencyV3, error) {

	now := time.Now()

	/* ---------- READ CACHE ---------- */
	cacheMutex.RLock()

	item, ok := currencyCache[code]

	if ok && now.Before(item.expiresAt) {
		cacheMutex.RUnlock()
		return item.data, nil
	}

	cacheMutex.RUnlock()

	/* ---------- FETCH DB ---------- */

	data, err := GetTodayCurrencyV3(db, code)
	if err != nil {
		return nil, err
	}

	/* ---------- WRITE CACHE ---------- */

	cacheMutex.Lock()

	currencyCache[code] = currencyCacheItem{
		data:      data,
		expiresAt: now.Add(cacheTTL),
	}

	cacheMutex.Unlock()

	return data, nil
}
