type ShutdownHandler = () => Promise<void>;

export class Lifecycle {
  private shutdownHandlers: ShutdownHandler[] = [];
  private shuttingDown = false;
  private _isRunning = true;

  get isRunning(): boolean {
    return this._isRunning;
  }

  onShutdown(handler: ShutdownHandler): void {
    this.shutdownHandlers.push(handler);
  }

  async shutdown(): Promise<void> {
    if (this.shuttingDown) {return;}
    this.shuttingDown = true;
    this._isRunning = false;

    console.log('Shutting down...');

    // Execute handlers in reverse order (LIFO)
    for (const handler of [...this.shutdownHandlers].reverse()) {
      try {
        await handler();
      } catch (error) {
        console.error('Shutdown handler error:', error);
      }
    }

    console.log('Shutdown complete');
  }
}
