import { useAuthStore } from '@/stores/auth';
import { TokenStorage } from '@/services/tokenStorage';
import { getMe } from '@/services/api/auth';
import { useQuery } from '@tanstack/react-query';

export const useAuth = () => {
  const {
    user,
    isAuthenticated,
    logout: storeLogout,
  } = useAuthStore();

  const logout = async () => {
    // Le store gère déjà le logout via la méthode logout
    await storeLogout();
  };

  // Optional: Query to sync user profile if we have a token but maybe stale user data
  // or to verify token validity on app load
  const accessToken = TokenStorage.getAccessToken();
  useQuery({
    queryKey: ['auth', 'me'],
    queryFn: getMe,
    enabled: !!accessToken && !user,
    retry: false,
  });

  return {
    user,
    accessToken: accessToken || null,
    refreshToken: TokenStorage.getRefreshToken() || null,
    isAuthenticated,
    logout,
  };
};
