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