import db from "../models/index.js";

const { Currency } = db;

// In-memory cache to prevent database hits on every single transaction
let activeCurrenciesCache = null;
let lastCacheTime = 0;
const CACHE_TTL_MS = 1000 * 60 * 5; // 5 minutes

/**
 * Validates if a currency code is currently active in the database.
 * Uses a short-lived memory cache to ensure high performance during transactions.
 * 
 * @param {string} code - The currency code to validate (e.g., 'NGN', 'USD')
 * @returns {Promise<boolean>}
 */
export const isCurrencyActive = async (code) => {
  if (!code) return false;

  const now = Date.now();
  
  // Refresh cache if it's empty or expired
  if (!activeCurrenciesCache || (now - lastCacheTime > CACHE_TTL_MS)) {
    try {
      const activeCurrencies = await Currency.findAll({
        where: { status: "active" },
        attributes: ["code"]
      });
      activeCurrenciesCache = new Set(activeCurrencies.map(c => c.code));
      lastCacheTime = now;
    } catch (error) {
      console.error("Failed to load active currencies from database:", error);
      // Fallback: if database fails, allow NGN and USD as core defaults to prevent system outage
      return ["NGN", "USD"].includes(code.toUpperCase());
    }
  }

  return activeCurrenciesCache.has(code.toUpperCase());
};

/**
 * Force clear the cache (useful when an admin updates a currency status)
 */
export const clearCurrencyCache = () => {
  activeCurrenciesCache = null;
  lastCacheTime = 0;
};
