'use strict';

const os = require('os');

const LOW_MEMORY_ENV_DEFAULTS = Object.freeze({
  DB_POOL_MAX: '2',
  DB_POOL_MIN: '1',
  DB_POOL_IDLE: '10000',
  CACHE_MAX_ENTRIES: '50',
  CACHE_TTL_METRICAS: '10000',
  CACHE_TTL_MESAS: '10000',
  CACHE_TTL_CANCEL: '10000',
  CACHE_TTL_GRAFICAS: '20000',
  CACHE_TTL_PRODUCTOS: '30000',
  CACHE_TTL_SERVICIO: '30000',
  CACHE_TTL_PAGOS: '30000',
  CACHE_TTL_MES: '120000',
  CACHE_TTL_CAJA: '20000',
});

function configureLowMemoryMode({ logger, totalMemoryBytes = os.totalmem() }) {
  const totalRamGb = totalMemoryBytes / (1024 ** 3);
  const enabled = process.env.LOW_MEMORY === 'true' || totalRamGb <= 4.5;
  if (!enabled) return { enabled, totalRamGb };
  logger.info(`Modo bajo consumo activado (RAM total: ${totalRamGb.toFixed(1)}GB)`);
  for (const [key, value] of Object.entries(LOW_MEMORY_ENV_DEFAULTS)) {
    if (!process.env[key]) process.env[key] = value;
  }
  if (global.gc) {
    setInterval(() => {
      try { global.gc(); } catch (_) {}
    }, 120_000).unref();
    logger.info('GC manual programado cada 2 min');
  }
  return { enabled, totalRamGb };
}

module.exports = { LOW_MEMORY_ENV_DEFAULTS, configureLowMemoryMode };
