import{useInfiniteQuery as y}from"@tanstack/react-query";import{useMemo as m,useRef as S}from"react";import{withPathPrefix as F}from"@redocly/theme/core/utils";import{getNextPageParam as R}from"../../../utils/catalog/get-next-page-param";import{useSearchTracker as b}from"./useSearchTracker";function E({entityKey:g,limit:o=20,filter:i,sort:s="updated_at",search:r},n){const l=n?n.items.map(e=>e.key).join("-"):[],c=S(!0),h=c.current&&n;c.current&&(c.current=!1);const t=y({queryFn:async e=>{const a=new URLSearchParams;i&&a.append("filter",i),s&&a.append("sort",s),o&&a.append("limit",o.toString()),r&&a.append("search",r),e.pageParam&&Object.entries(e.pageParam).forEach(([w,f])=>{f!=null&&a.append(w,f.toString())});const p=new URL(F(`/bff/catalog-related-entities/${g}`),window.location.origin);p.search=a.toString();const d=await fetch(p.toString());if(!d.ok)throw new Error(`Failed to fetch catalog entity relations from ${p.pathname}`);return d.json()},queryKey:["bff/catalog-entities-relations",{limit:o,filter:i,sort:s,search:r,entityKey:g,initialDataKeys:l}],initialPageParam:null,initialData:h?{pages:[n],pageParams:[null]}:void 0,refetchOnMount:!0,getNextPageParam:R}),P=m(()=>{const e=t.data?.pages||[];return e[e.length-1]?.page?.total},[t.data?.pages]),u=m(()=>(t.data?.pages||[]).flatMap(e=>e.items||[]),[t.data?.pages]);return b({isLoading:t.isLoading||t.isFetching,items:u,apiResource:"related_entities",searchQuery:r??""}),{query:t,items:u,total:P}}export{E as useFetchCatalogEntitiesRelations};
