// server/utils/cleanupManager.js
const logger = require("./logger");

let cleanupTasks = [];
let isShuttingDown = false;

/**
 * Register a cleanup task to be executed during shutdown
 * @param {Function} task - The cleanup task to register
 */
function registerCleanupTask(task) {
  cleanupTasks.push(task);
}

/**
 * Handle SIGTERM signal for graceful shutdown
 */
async function handleSigterm() {
  if (isShuttingDown) {
    logger.log("sigterm-api", "WARN", null, null, { message: "Shutdown already in progress, ignoring signal." });
    return;
  }

  isShuttingDown = true;

  logger.log("sigterm-api", "WARN", null, null, { message: "SIGTERM Received. Starting graceful shutdown." });

  try {
    for (const task of cleanupTasks) {
      logger.log("sigterm-api", "WARN", null, null, { message: `Running cleanup task: ${task.name}` });
      await task();
    }
    logger.log("sigterm-api", "WARN", null, null, { message: `All cleanup tasks completed.` });
  } catch (error) {
    logger.log("sigterm-api-error", "ERROR", null, null, { message: error.message, stack: error.stack });
  }

  process.exit(0);
}

/**
 * Initialize cleanup manager with process event listeners
 */
function initializeCleanupManager() {
  process.on("SIGTERM", handleSigterm);
  process.on("SIGINT", handleSigterm); // Handle Ctrl+C
}

module.exports = {
  registerCleanupTask,
  initializeCleanupManager
};
