import { logout } from "../services/users.service";
import { deleteToken } from "firebase/messaging";
import { getMessagingInstance } from "../config/firebase";

export const isLoggedIn = () => {
  let redux = JSON.parse(localStorage.getItem("redux"));
  if (redux?.login?.user) {
    return true;
  }
  return false;
};

export function capitalizeFirstLetter(string) {
  return string.charAt(0).toUpperCase() + string.slice(1);
}

export function capitalizeAllLetters(string) {
  return string.toUpperCase();
}


export const resetLocalStorage = () => {
  Object.keys(localStorage).forEach((key) => {
    localStorage.removeItem(key);
  });
};

export const isBSPortal = () => {
  let redux = JSON.parse(localStorage.getItem("redux"));
  const isSuperAdmin = redux?.login?.user?.isSuperAdmin;
  return { isSuperAdmin };
};

export const commonLogoutFunc = async () => {
  try {
    // await logout();
    resetLocalStorage();
    // Try to delete the Firebase messaging token, but don't let it block logout if it fails
    try {
      await deleteToken(messaging);
    } catch (error) {
      console.warn('Failed to delete Firebase messaging token:', error);
      // Continue with logout even if token deletion fails
    }
    window.location.replace("/");
  } catch (error) {
    console.error('Error during logout:', error);
    // Ensure user is still logged out even if there's an error
    resetLocalStorage();
    window.location.replace("/");
  }
};

export const checkModulePermission = (moduleName) => {
  let redux = JSON.parse(localStorage.getItem("redux"));
  const userPermissions = redux?.login?.user?.permissions ?? [];
  let hasAccess = false;
  if (moduleName && userPermissions) {
    for (let permission of userPermissions) {
      let trimmedPermissions = permission.replace("CREATE_", "");
      trimmedPermissions = permission.replace("READ_", "");
      trimmedPermissions = permission.replace("DELETE_", "");
      if (trimmedPermissions.includes(moduleName)) {
        hasAccess = true;
        break;
      }
    }
    return hasAccess;
  }
  return true;
};
