// ============================================================
// CONFIG.JS — DB-backed app config with in-memory cache
// Falls back to provided defaults if DB is unavailable
// ============================================================

const db = require('../db/database');

const _cache = {};
const CACHE_TTL = 2 * 60 * 1000; // 2 minutes

async function get(key, defaultVal) {
  const now = Date.now();
  if (_cache[key] && (now - _cache[key].ts) < CACHE_TTL) {
    return _cache[key].value;
  }
  try {
    const val = await db.getSetting(key);
    const result = (val !== null && val !== undefined) ? val : (defaultVal !== undefined ? defaultVal : null);
    _cache[key] = { value: result, ts: now };
    return result;
  } catch (e) {
    return defaultVal !== undefined ? defaultVal : null;
  }
}

async function set(key, value) {
  await db.setSetting(key, String(value));
  _cache[key] = { value: String(value), ts: Date.now() };
}

function invalidate(key) {
  if (key) {
    delete _cache[key];
  } else {
    Object.keys(_cache).forEach(k => delete _cache[k]);
  }
}

async function getByPrefix(prefix) {
  try {
    const rows = await db.all(
      "SELECT key, value, updated_at FROM app_settings WHERE key LIKE $1 ORDER BY key",
      [prefix + '%']
    );
    rows.forEach(r => { _cache[r.key] = { value: r.value, ts: Date.now() }; });
    return rows;
  } catch (e) {
    return [];
  }
}

module.exports = { get, set, invalidate, getByPrefix };
