import { useEffect } from 'react';

import isNil from 'lodash-es/isNil';

import { tokenManager } from 'src/config/tokens';
import {
  clearLogoutCallbacksFlag,
  didLogoutRunCallbacks,
} from 'src/contexts/beforeLogoutCallbacks';
import { useAuth } from 'src/contexts/JWTContext';
import { deleteMessagingToken, removeNotificationToken } from '../services';

/**
 * Registers a cleanup that removes the notification token before auth logout
 * (so the DELETE runs while still authenticated). Runs the same cleanup on unmount.
 */
export function useNotificationLogoutCleanup(
  notificationsToken: string | null,
  setNotificationsToken: React.Dispatch<React.SetStateAction<string | null>>,
): void {
  const { registerBeforeLogoutCallback } = useAuth();

  useEffect(() => {
    const removeToken = async () => {
      try {
        const { accessToken } = tokenManager.getCorrectToken();
        const isValidToken = tokenManager.isTokenValid();
        if (!isNil(notificationsToken) && !isNil(accessToken) && isValidToken) {
          await removeNotificationToken(notificationsToken, accessToken);
          await deleteMessagingToken();
          setNotificationsToken(null);
        }
      } catch (_err) {
        // Ignore (e.g. already logged out or network error)
      }
    };

    const unregister =
      registerBeforeLogoutCallback?.(removeToken) ?? (() => undefined);
    return () => {
      unregister();
      if (didLogoutRunCallbacks()) {
        clearLogoutCallbacksFlag();
        return;
      }
      void removeToken();
    };
  }, [notificationsToken, registerBeforeLogoutCallback, setNotificationsToken]);
}
