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