function createReconnectOutboxes({
  refresh,
  restoreIdentity,
  flushIssue,
  flushAuthored,
  flushNotificationReads,
}) {
  let activeReconnect = null;
  let followUpRequested = false;

  async function reconnectOnce() {
    const snapshot = await refresh();
    const freshness = snapshot?.freshness?.sections?.context;
    const identityFresh = snapshot?.context && !snapshot.context.error &&
      !freshness?.stale && !freshness?.degraded && !freshness?.revalidating;
    const login = identityFresh ? String(snapshot.context.user?.login || '').trim() : '';
    if (!login) return false;
    restoreIdentity(login);
    await Promise.all([
      flushIssue(),
      flushAuthored(),
      flushNotificationReads(),
    ]);
    return true;
  }

  return function reconnectOutboxes() {
    if (activeReconnect) {
      followUpRequested = true;
      return activeReconnect;
    }
    activeReconnect = (async () => {
      let result = false;
      do {
        followUpRequested = false;
        result = await reconnectOnce();
      } while (followUpRequested);
      return result;
    })().finally(() => { activeReconnect = null; });
    return activeReconnect;
  };
}

if (typeof module !== 'undefined' && module.exports) module.exports = createReconnectOutboxes;
