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