export type ExitGuardCanDispose = () => Promise<boolean>;

export abstract class ExitGuardManager {
  abstract register(id: string, canDispose: ExitGuardCanDispose): void;
  abstract unregister(id: string): void;
  abstract canExit(): Promise<boolean>;
}

export class ExitGuardManagerImpl implements ExitGuardManager {
  private guards = new Map<string, ExitGuardCanDispose>();

  register(id: string, canDispose: ExitGuardCanDispose): void {
    this.guards.set(id, canDispose);
  }

  unregister(id: string): void {
    this.guards.delete(id);
  }

  async canExit(): Promise<boolean> {
    for (const guard of this.guards.values()) {
      try {
        const can = await guard();
        if (!can) return false;
      } catch (e) {
        console.error("Exit guard failed:", e);
      }
    }
    return true;
  }
}
