import{writeFile as E,readFile as w,rm as D,readdir as g}from"node:fs/promises";import R from"fs";import h from"node:path";import{SEARCH_GROUP_FACET_FIELD as $,SEARCH_PRODUCT_FIELD as v,SEARCH_VERSION_FIELD as y}from"../../../../../constants/index.js";import{ensureDir as I}from"../../../../utils/index.js";import{SEARCH_INDEX_FIELDS as A,SEARCH_DATA_EXPORT_FOLDER as m}from"../../constants.js";import{FlexSearchIndex as C}from"./search-index.js";class b{indexes=new Map;indexSchema;async initIndexSchema(s){this.indexSchema={document:{id:"id",tag:"tags",index:A},worker:!1,tokenize:"forward",context:{depth:2,resolution:9}}}getIndex(s,i){const e=this.indexes.get(i);if(e)return e.find(n=>n.id===s)}createIndex(s,i){let e=this.getIndex(s,i);return e||(e=new C(s,this.indexSchema),this.indexes.set(i,[...this.indexes.get(i)??[],e])),e}addDocuments(s,i,e){e.length&&this.createIndex(s,i).add(e)}async search(s,i){const{query:e,locale:n,filter:c,loadMore:o,auth:d}=s,r=this.indexes.get(n)??[];let a=[],l="",p=["v:default"];if(c)for(const t of c)t.field===$?a=[...a,...t.values]:t.field===v?l=`p:${t.values[0]}`:t.field===y&&t.values.length&&t.values.length===2&&(p=[...p,`v:${t.values[0]}:${t.values[1]}`]);const F={auth:d,query:e,offset:0,SEARCH_GROUP_FACET_FIELD:$,product:l,versions:p},u=[];let f={facets:{},documents:{}};if(o){const t=this.getIndex(o.groupKey,n);t&&u.push(t.search({...F,offset:o.offset}))}else for(const t of r)a&&a.length?a.includes(t.id)&&u.push(t.search(F)):u.push(t.search(F));return await Promise.all(u).then(t=>{for(const S of t){f.documents={...f.documents,...S.documents};for(const[x,_]of Object.entries(S.facets))f.facets[x]?f.facets[x]=[...f.facets[x],..._]:f.facets[x]=_}}),f}async export(s){R.existsSync(`${s}/${m}`)&&await D(`${s}/${m}`,{recursive:!0});const i=I(h.join(s,m));for(const[e,n]of this.indexes){const c=I(h.join(i,e));for(const o of n){const d=I(h.join(c,`${o.id}.json`)),r={documents:[],index:{}};r.documents=Array.from(o.documents),await o.export((a,l)=>{r.index[a]=l}),await E(d,JSON.stringify(r),"utf-8")}}}async import(s){const i=`${s}/${m}`,e=await g(i);for(const n of e){const c=await g(`${i}/${n}`);for(const o of c){const d=`${i}/${n}/${o}`,r=JSON.parse(await w(d,"utf-8")),a=h.parse(o).name;await this.createIndex(a,n).import(r)}}}countFacets(s,i){const e={};for(const[n,c]of i)e[n]=c.values.map(o=>({value:o,count:0,isCounterVisible:!1}));return e}cleanupFacetValues(s){}}export{b as FlexSearch};
