/*  Bitmap Based Roles
 *  User role === 1
 *  Editor role === 2
 *  Admin role === 4
 *  Admin and editor role === 6
 *  Highest role is 7
 */
export enum Role {
  USER = 1, // 001
  EDITOR = 2, // 010
  ADMIN = 4, // 100
}

export function hasPermission(userRole: number, requiredRole: Role): boolean {
  return (userRole & requiredRole) !== 0;
}

type RoleDefinition = {
  name: string;
  color: {
    bg: string;
    fg: string;
    border: string;
  };
};

export const roleDefinitions: { [key: number]: RoleDefinition } = {
  [Role.USER]: {
    name: "User",
    color: {
      bg: "bg-muted",
      fg: "text-muted-foreground",
      border: "border-muted-foreground",
    },
  },
  [Role.EDITOR]: {
    name: "Editor",
    color: {
      bg: "bg-blue-300",
      fg: "text-blue-700",
      border: "border-blue-700",
    },
  },
  [Role.ADMIN]: {
    name: "Admin",
    color: {
      bg: "bg-destructive",
      fg: "text-destructive-foreground",
      border: "border-destructive",
    },
  },
};

export const roleDefinitionsArray = Object.entries(roleDefinitions).map(
  ([key, role]) => ({
    key,
    role,
  }),
);

export function getUserPermissions(userRole: number): RoleDefinition[] {
  return Object.keys(roleDefinitions)
    .map(Number) // Convert keys to numbers
    .filter((role) => (userRole & role) !== 0) // Check if role is set
    .map((role) => roleDefinitions[role]!); // Convert back to role name
}
