import { defineStore } from "pinia";
import type { PermissionModule, PermissionObject, PermissionSection, PermissionType } from "@/types/permissionTypes";

export const useAbilityStore = defineStore("ability", {
  state: () => {
    return {
      permissions: {} as PermissionObject,
      isOwner: false as boolean,
    };
  },
  getters: {
    can:
      (state) =>
      (type: PermissionType | "admin", section: PermissionSection, module?: PermissionModule): boolean => {
        const permissions = state.permissions;
        if (state.isOwner) return true;
        if (type == "admin") return permissions?.admin ?? false;
        if (permissions?.admin) return true;
        if (
          (!module &&
            permissions[section] != undefined &&
            (permissions[section]?.all == "*" || permissions[section]?.all?.includes(type))) ||
          permissions[section]?.all == "*" ||
          permissions[section]?.all?.includes(type)
        )
          return true;
        if (module && (permissions[section]?.[module] == "*" || permissions[section]?.[module]?.includes(type)))
          return true;
        return false;
      },
    canSection:
      (state) =>
      (type: PermissionType | "admin", section: PermissionSection): boolean => {
        const permissions = state.permissions;
        if (state.isOwner) return true;
        if (type == "admin") return permissions?.admin ?? false;
        if (permissions?.admin) return true;
        if (
          permissions[section]?.all == "*" ||
          permissions[section]?.all?.includes(type) ||
          permissions[section] != undefined
        )
          return true;
        return false;
      },
    _can:
      () =>
      (
        permissions: PermissionObject,
        type: PermissionType | "admin",
        section: PermissionSection,
        module?: PermissionModule
      ): boolean => {
        // ignores ownership
        if (type == "admin") return permissions?.admin ?? false;
        if (permissions?.admin) return true;
        if (
          (!module &&
            permissions[section] != undefined &&
            (permissions[section]?.all == "*" || permissions[section]?.all?.includes(type))) ||
          permissions[section]?.all == "*" ||
          permissions[section]?.all?.includes(type)
        )
          return true;
        if (module && (permissions[section]?.[module] == "*" || permissions[section]?.[module]?.includes(type)))
          return true;
        return false;
      },
  },
  actions: {
    setAbility(permissions: PermissionObject, isOwner: boolean) {
      this.permissions = permissions;
      this.isOwner = isOwner;
    },
  },
});
