import type { FastifyInstance } from 'fastify';

export interface ShutdownDeps {
  disconnectDb: () => Promise<void>;
}

export function setupGracefulShutdown(
  app: FastifyInstance,
  deps: ShutdownDeps,
  processRef: NodeJS.Process = process,
): void {
  let shuttingDown = false;

  const shutdown = async (signal: string): Promise<void> => {
    if (shuttingDown) return;
    shuttingDown = true;

    app.log.info(`Received ${signal}, shutting down gracefully...`);

    try {
      await app.close();
      await deps.disconnectDb();
      app.log.info('Server shut down successfully');
    } catch (err) {
      app.log.error(err, 'Error during shutdown');
    }

    processRef.exit(0);
  };

  processRef.on('SIGTERM', () => { void shutdown('SIGTERM'); });
  processRef.on('SIGINT', () => { void shutdown('SIGINT'); });
}
