import { toast } from 'react-toastify';

export const performLogout = async (dispatch, logoutAPI, logout, resetApiState) => {
  try {
    if (logoutAPI) {
      await logoutAPI().unwrap();
    }

    localStorage.removeItem("userData");
    localStorage.removeItem("userdata");
    sessionStorage.clear();

    if (dispatch && logout) {
      dispatch(logout());
    }
    if (dispatch && resetApiState) {
      dispatch(resetApiState());
    }

    window.location.href = "/";
    
    toast.success("Logged out successfully!");
  } catch (error) {
    console.error('Logout error:', error);
    localStorage.removeItem("userData");
    localStorage.removeItem("userdata");
    sessionStorage.clear();
    
    if (dispatch && logout) {
      dispatch(logout());
    }
    if (dispatch && resetApiState) {
      dispatch(resetApiState());
    }
    
    window.location.href = "/";
    toast.success("Logged out successfully!");
  }
};

export const isAuthenticated = () => {
  const userData = localStorage.getItem('userData');
  return !!userData;
};

export const getUserData = () => {
  const userData = localStorage.getItem('userData');
  return userData ? JSON.parse(userData) : null;
};

export const clearAuthData = () => {
  localStorage.removeItem("userData");
  localStorage.removeItem("userdata");
  sessionStorage.clear();
};