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