import { useCallback, useMemo } from 'react';
import { getRoleDefaultDisplayName } from './getRoleDefaultDisplayName.mjs';
import { ROLE_ID_STYTCH_MEMBER, ROLE_ID_STYTCH_ADMIN } from './roles.mjs';
import { useGetRoleDisplayName } from './useGetRoleDisplayName.mjs';
import { useGetRoleSortOrder } from './useGetRoleSortOrder.mjs';
import { useRoles } from './useRoles.mjs';

const wellKnownRoleIds = [
    ROLE_ID_STYTCH_MEMBER,
    ROLE_ID_STYTCH_ADMIN
];
/**
 * A sort comparison function for role IDs that prioritizes certain well-known
 * role IDs over others. Non-well-known roles are considered equivalent, so
 * their order is preserved.
 */ const compareWellKnownRoleIds = (a, b)=>{
    if (a === b) {
        return 0;
    }
    for (const roleId of wellKnownRoleIds){
        if (a === roleId) {
            return -1;
        }
        if (b === roleId) {
            return 1;
        }
    }
    return 0;
};
const useRolesById = ()=>{
    const getRoleDisplayName = useGetRoleDisplayName();
    const allRoles = useRoles();
    return useMemo(()=>allRoles?.reduce((acc, role)=>{
            acc[role.role_id] = {
                ...role,
                displayName: getRoleDisplayName(role) || getRoleDefaultDisplayName(role)
            };
            return acc;
        }, {}), [
        allRoles,
        getRoleDisplayName
    ]);
};
const useRoleSortFn = ()=>{
    const rolesById = useRolesById();
    const sort = useGetRoleSortOrder();
    return useCallback((roles)=>{
        const rolesWithDisplayNames = roles.map((role)=>{
            const matchingPolicyRole = rolesById?.[role.role_id];
            const rbacRole = {
                role_id: matchingPolicyRole?.role_id ?? role.role_id,
                description: matchingPolicyRole?.description ?? '',
                permissions: matchingPolicyRole?.permissions ?? []
            };
            return {
                ...rbacRole,
                ...role,
                displayName: matchingPolicyRole?.displayName ?? role.role_id
            };
        });
        const preSortedRoles = rolesWithDisplayNames.sort((a, b)=>{
            return compareWellKnownRoleIds(a.role_id, b.role_id) || a.displayName.localeCompare(b.displayName);
        });
        return sort(preSortedRoles);
    }, [
        rolesById,
        sort
    ]);
};

export { useRoleSortFn, useRolesById };
//# sourceMappingURL=useRoleSortFn.mjs.map
