import {
  TEAM_PERMISSIONS_BY_ROLE,
  AVAILABLE_ROLES,
  ROLE_HIERARCHY,
  ROLE_DESCRIPTIONS
} from "@nextsparkjs/registries/permissions-registry";
const ALL_TEAM_PERMISSIONS = [
  "team.view",
  "team.edit",
  "team.delete",
  "team.members.view",
  "team.members.invite",
  "team.members.remove",
  "team.members.update_role",
  "team.settings.view",
  "team.settings.edit",
  "team.billing.view",
  "team.billing.manage"
];
function getPermissionsFromRegistry() {
  return TEAM_PERMISSIONS_BY_ROLE;
}
function getHierarchyFromRegistry() {
  return ROLE_HIERARCHY;
}
function getAvailableRolesFromRegistry() {
  return AVAILABLE_ROLES;
}
function getDescriptionsFromRegistry() {
  return ROLE_DESCRIPTIONS;
}
const rolePermissions = getPermissionsFromRegistry();
function hasPermission(role, permission, isGlobalAdmin = false) {
  var _a;
  if (isGlobalAdmin) {
    return true;
  }
  const permissions = getPermissionsFromRegistry();
  return ((_a = permissions[role]) == null ? void 0 : _a.includes(permission)) || false;
}
function getRolePermissions(role, isGlobalAdmin = false) {
  if (isGlobalAdmin) {
    return ALL_TEAM_PERMISSIONS;
  }
  const permissions = getPermissionsFromRegistry();
  return permissions[role] || [];
}
function checkTeamPermission(userRole, teamRole, permission) {
  var _a;
  if (userRole === "superadmin") {
    return true;
  }
  if (!teamRole) {
    return false;
  }
  const permissions = getPermissionsFromRegistry();
  return ((_a = permissions[teamRole]) == null ? void 0 : _a.includes(permission)) || false;
}
function isSuperadmin(userRole) {
  return userRole === "superadmin";
}
function canManageRole(actorRole, targetRole) {
  const hierarchy = getHierarchyFromRegistry();
  return (hierarchy[actorRole] ?? 0) > (hierarchy[targetRole] ?? 0);
}
function getRoleDescription(role) {
  const descriptions = getDescriptionsFromRegistry();
  return descriptions[role] ?? "No description available";
}
function isInvitableRole(role) {
  return role !== "owner";
}
function getInvitableRoles() {
  const availableRoles = getAvailableRolesFromRegistry();
  return [...availableRoles].filter((role) => role !== "owner");
}
function validateRoleTransition(fromRole, toRole, actorRole) {
  if (fromRole === "owner") {
    return {
      allowed: false,
      reason: "Owner role cannot be changed. Use ownership transfer instead."
    };
  }
  if (toRole === "owner") {
    return {
      allowed: false,
      reason: "Cannot promote to owner. Use ownership transfer instead."
    };
  }
  if (!canManageRole(actorRole, fromRole)) {
    return {
      allowed: false,
      reason: "You do not have permission to change this user's role."
    };
  }
  return { allowed: true };
}
export {
  ALL_TEAM_PERMISSIONS,
  canManageRole,
  checkTeamPermission,
  getInvitableRoles,
  getRoleDescription,
  getRolePermissions,
  hasPermission,
  isInvitableRole,
  isSuperadmin,
  rolePermissions,
  validateRoleTransition
};
