export const permissionsHandler = {
  computed: {
    loggedUser() {
      return this.$store.state.user || {};
    },
    isReady() {
      return this.loggedUser && Object.keys(this.loggedUser).length > 0;
    },
    permissions() {
      return this.isReady && this.loggedUser.role.permissions;
    },
    routePathString() {
      return this.$store.state.routes[this.$route.name] || "";
    },
    isAdministrator() {
      if (!this.loggedUser.role_id) {
        return true;
      }
      const userPermissions = this.permissions;
      if (userPermissions) {
        return (
          userPermissions.settings.accessible &&
          userPermissions.reports.accessible &&
          userPermissions.leads.accessible &&
          userPermissions.reports.sales_report.every((e) =>
            ["C", "R", "U", "D"].includes(e)
          )
        );
      }
      return false;
    },
  },
  methods: {
    hasPermissionTo(permission) {
      /**
       * permission ==> CRUD
       */
      if (!this.loggedUser.role_id) {
        return true;
      }

      let access = this.routePathString
        .split(".")
        .reduce((a, b) => (a && a[b]) || null, this.permissions);
      return access && access.includes(permission);
    },
  },
};
