// {{ display_name }} MCP server — generated by mcpify. Do not hand-edit.

import { logger } from './logger.js';

type CleanupFn = () => Promise<void> | void;

const cleanupFns: CleanupFn[] = [];
let shuttingDown = false;

/** Registers a cleanup callback, run in reverse registration order during shutdown. */
export function onShutdown(fn: CleanupFn): void {
  cleanupFns.push(fn);
}

async function shutdown(signal: string): Promise<void> {
  if (shuttingDown) return;
  shuttingDown = true;
  logger.info({ signal }, 'shutting down');

  for (const fn of [...cleanupFns].reverse()) {
    try {
      await fn();
    } catch (error) {
      logger.error({ err: error }, 'error during shutdown cleanup');
    }
  }
  process.exit(0);
}

/** Installs SIGINT/SIGTERM handlers for graceful termination — REQ-2.3.4. */
export function installShutdownHandlers(): void {
  process.once('SIGINT', () => void shutdown('SIGINT'));
  process.once('SIGTERM', () => void shutdown('SIGTERM'));
}
