import{telemetryTraceStep as C}from"../../telemetry/helpers/trace-step.js";import{CACHE_CONTROL_NO_STORE_HEADER_VALUE as T}from"../../constants/common.js";import{expandTeamsForRead as E}from"../../utils/rbac.js";function F(e){return async t=>(t.header("Cache-Control",T),await C("search",async s=>{const i=t.get("logger"),a=t.get("auth"),A=i.startTiming(),o=e.getConfig().access?.requiresLogin&&!a.isAuthenticated,u=t.req.valid("json");s?.setAttribute("engine",e?.searchEngine?.type),s?.setAttribute("query",u.query||""),s?.setAttribute("user",a.claims.email??"anonymous"),s?.setAttribute("noAccess",o);const g=e.getSearchFacets(),r=o?{}:e.searchEngine?await e.searchEngine.search(u,{...a,teams:E(e.config.access?.rbac,a.teams)},g):{};let l=0;if(Object.keys(r).length){const f=r.documents;for(const[c,n]of Object.entries(f))l+=n.length}return i.infoTime(A,`Search with query "${u.query||""}". Total results: ${l}`),s?.setAttribute("resultsCount",l),t.json(r)}))}function j(e){return async t=>(t.header("Cache-Control",T),await C("search.facets",async s=>{const i=t.get("logger"),a=t.get("auth"),m=e.getConfig().access?.requiresLogin&&!a.isAuthenticated,o=t.req.valid("json");s?.setAttribute("engine",e?.searchEngine?.type),s?.setAttribute("user",a.claims.email??"anonymous"),s?.setAttribute("noAccess",m);const u=i.startTiming(),g=e.getSearchFacets(),r=m?{}:e.searchEngine?await e.searchEngine.countFacets(o,a,g):{},l=!!o.field;let f=[];if(l){const c=o.field,n=c&&g.get(c);if(n){const h={...n};h.values=r?.[c]||[],f.push(h)}}else{const c=new Map;for(const[n,h]of g){const y=r?.[n],d={...h};d.values=y||h.values.map(b=>({value:b,count:0})),c.set(n,d)}f=Array.from(c,([,n])=>n)}return i.verboseTime(u,"Search facets"),t.json(f)}))}export{j as searchFacetsHandler,F as searchHandler};
