import store from '@/store';
import jwtDecode from 'jwt-decode';
import { Claims } from '@/api/types';
import * as luxon from 'luxon';

const removeToken = () => {
  sessionStorage.removeItem('jwt');
  store.commit('clearToken');
};
const hasPermission = (requiredRights: number) => {
  const jwt = store.getters.getToken;
  if (jwt !== undefined && requiredRights !== undefined) {
    try {
      const decoded = jwtDecode<Claims>(store.getters.getToken);
      const expired = luxon.DateTime.now()
        .toUnixInteger() > decoded.exp;
      jwtDecode(jwt, { header: true });
      if (!expired && decoded.privileges <= requiredRights) {
        return true;
      }
      if (expired) {
        removeToken();
      }
      return false;
    } catch {
      removeToken();
      return false;
    }
  }
  return !(jwt === undefined && requiredRights !== undefined);
};

export default hasPermission;
