// assets/js/utils/auth.js
const AuthUtils = {
  getToken: () => localStorage.getItem("token"),

  setToken: (token) => localStorage.setItem("token", token),

  removeToken: () => localStorage.removeItem("token"),

  getCurrentUser: () => {
    const user = localStorage.getItem("user");
    return user ? JSON.parse(user) : null;
  },

  setCurrentUser: (user) => {
    localStorage.setItem("user", JSON.stringify(user));
  },

  removeCurrentUser: () => {
    localStorage.removeItem("user");
  },

  clearAuth: () => {
    localStorage.clear();
  },

  isAuthenticated: () => {
    return !!AuthUtils.getToken();
  },

  hasRole: (role) => {
    const user = AuthUtils.getCurrentUser();
    return user && user.role === role;
  },

  redirectBasedOnRole: (user) => {
    if (!user || !user.role) {
      window.location.href = "/login";
      return;
    }

    const redirectMap = {
      admin: "/admin",
      manager: "/manager",
      user: "/user",
    };

    window.location.href = redirectMap[user.role] || "/login";
  },

  checkAuthAndRedirect: (requiredRole = null) => {
    const user = AuthUtils.getCurrentUser();

    if (!AuthUtils.isAuthenticated() || !user) {
      window.location.href = "/login";
      return false;
    }

    if (requiredRole && user.role !== requiredRole) {
      AuthUtils.redirectBasedOnRole(user);
      return false;
    }

    return true;
  },
};
