'use strict';

function registerProcessSupervision({ logger, lowMemory, runtimeProcess = process }) {
  runtimeProcess.on('uncaughtException', (error) => {
    logger.error('uncaughtException - proceso terminando para reinicio del servicio', { stack: error.stack });
    runtimeProcess.exit(1);
  });

  let rejectionCount = 0;
  let rejectionTimer = null;
  runtimeProcess.on('unhandledRejection', (reason) => {
    const message = reason instanceof Error ? reason.message : String(reason);
    logger.error('unhandledRejection', { reason: message });
    rejectionCount += 1;
    if (!rejectionTimer) {
      rejectionTimer = setTimeout(() => {
        rejectionCount = 0;
        rejectionTimer = null;
      }, 60_000);
    }
    if (rejectionCount > 20) {
      logger.error('Demasiados rechazos no capturados - reiniciando', { rejectionCount, reason: message });
      runtimeProcess.exit(1);
    }
  });

  if (process.env.NODE_ENV === 'production' || process.env.ARKHON_SERVICE === '1') {
    const intervalMs = lowMemory ? 2 * 60 * 1000 : 5 * 60 * 1000;
    setInterval(() => {
      const memoryMb = Math.round(runtimeProcess.memoryUsage().rss / 1024 / 1024);
      const warningMb = lowMemory ? 200 : 700;
      const criticalMb = lowMemory ? 280 : 900;
      if (memoryMb > criticalMb) {
        logger.error('Memoria critica - reiniciando proceso', { memoryMb, criticalMb });
        runtimeProcess.exit(1);
      } else if (memoryMb > warningMb) {
        logger.warn('Memoria alta', { memoryMb, warningMb });
      }
    }, intervalMs).unref?.();
  }
}

module.exports = { registerProcessSupervision };
