import { useSelector } from 'react-redux';
import { authStorage } from '../utils/auth-storage';
import type { AuthState } from '../types/auth.types';

/**
 * The current auth token, preferring Redux so components re-render on login
 * and logout. Falls back to storage for the one case Redux misses: both
 * `hydrateAuth` and the stores' `preloadedState` only populate `auth.token`
 * when a token *and* a cached user are present, so a session with a token but
 * no cached user would otherwise read as signed out.
 */
export function useAuthToken(): string | undefined {
  const token = useSelector((state: { auth: AuthState }) => state.auth.token);
  return token ?? authStorage.getToken();
}
