export default function usePermission() {
  // Permission-Based Access Control with Dynamic Role Creation

  // Utility to list all resources and their actions
  function listPermissions(permissions: TPermissions): {
    resource: string;
    actions: { title: string; description: string }[];
  }[] {
    return Object.entries(permissions).map(([resource, actions]) => ({
      resource,
      actions: Object.entries(actions).map(([action, { description }]) => ({
        title: action,
        description,
      })),
    }));
  }

  // Utility to check if a user has permission
  function hasPermission(
    user: TRole,
    permissions: TPermissions,
    resource: string,
    action: string,
    data?: any
  ): boolean {
    const permissionKey = `${resource}:${action}`;

    // Check if the permission exists in the user's permission array
    if (!user.permissions?.includes(permissionKey)) {
      return false;
    }

    const resourcePermissions = permissions[resource];
    if (!resourcePermissions || !resourcePermissions[action]) {
      return false;
    }

    const permissionCheck = resourcePermissions[action].check;

    // Evaluate the permission check
    if (typeof permissionCheck === "boolean") {
      return permissionCheck;
    } else if (typeof permissionCheck === "function") {
      return permissionCheck(user, data);
    }

    return false;
  }

  return {
    listPermissions,
    hasPermission,
  };
}
