import { create } from 'zustand';
import { UserWithRoles } from '@/types/api/api-general';

type AuthStore = {
  user?: UserWithRoles;
  isLoadingUser?: boolean;
  setUser: (newUserData?: UserWithRoles) => void;
  setIsLoadingUser: (isLoading?: boolean) => void;
  permissionCheck: (permissionName: string) => boolean;
};

const useAuthStore = create<AuthStore>()((set, get) => ({
  user: undefined,
  isLoadingUser: false,
  setUser: (newUserData) => set({ user: newUserData }),
  setIsLoadingUser: (isLoading) => set({ isLoadingUser: Boolean(isLoading) }),

  permissionCheck: (name) => {
    const { user, isLoadingUser } = get();

    if (!isLoadingUser && user) {
      const isAllowed = user.roles.some((role) => {
        const isPermissionNameAllowed = role.permissions.some(
          (permission) => permission.name === name
        );

        return isPermissionNameAllowed;
      });

      return isAllowed;
    }

    return false;
  },
}));

export const useAuth = () => {
  const { user, setUser, isLoadingUser, setIsLoadingUser, permissionCheck } =
    useAuthStore();

  return {
    user,
    setUser,
    isLoadingUser,
    setIsLoadingUser,
    permissionCheck,
  };
};
