import { defineStore } from 'pinia';
import api from '../api';
import { GroupPermission } from '@/types/group-permission';
import { Permissions } from '@/constants/permissions';

interface PermissionsDictionary {
  [key: string]: number;
}

export const usePermissionsStore = defineStore('permissions', () => {
  const all: Ref<PermissionsDictionary> = ref({});
  // TODO notifies store

  const getAll = async () => {
    const [res, e] = await api.permissions.getAll();
    if (e && typeof e === 'string') {
      // error.value = e;
      // TODO notify
    } else {
      all.value = res?.data ?? {};
    }
  };

  const isValid = (
    permissions: GroupPermission[],
    toExist: Permissions,
  ): boolean => {
    if (permissions?.length && permissions.find((i) => i.value === toExist)) {
      if (Object.values(all.value).find((i) => i === toExist)) {
        return true;
      }
    }

    return false;
  };

  const exist = (): boolean => Object.keys(all.value).length > 0;

  return {
    all,
    getAll,
    isValid,
    exist,
  };
});
