/**
 * Registry of callbacks to run before calling auth/logout (e.g. remove FCM token).
 * Kept outside JWTContext so the auth reducer is not mixed with subscription state.
 */

const callbacks: Array<() => Promise<void>> = [];

/** True from runCallbacks() until the effect cleanup that skipped removeToken calls clearLogoutCallbacksFlag(). */
let logoutCallbacksJustRan = false;

export const registerCallback = (fn: () => Promise<void>): (() => void) => {
  callbacks.push(fn);
  return () => {
    const index = callbacks.indexOf(fn);
    if (index !== -1) callbacks.splice(index, 1);
  };
};

/** True if runCallbacks() was just invoked (logout flow). Effect cleanups skip removeToken when true and then call clearLogoutCallbacksFlag(). */
export const didLogoutRunCallbacks = (): boolean => logoutCallbacksJustRan;

/** Reset the flag. Called from effect cleanup when skipping redundant removeToken. */
export const clearLogoutCallbacksFlag = (): void => {
  logoutCallbacksJustRan = false;
};

export const runCallbacks = (): Promise<void> => {
  logoutCallbacksJustRan = true;
  return Promise.all(callbacks.map(cb => cb().catch(() => null))).then(
    () => undefined,
  );
};
