import{eq as b,and as m,gte as l,gt as B,lt as g,asc as S,desc as R,or as f,isNull as K,sql as o,inArray as L,count as M}from"drizzle-orm";import{logger as C}from"../../../tools/notifiers/logger.js";import{kvTable as e}from"../../../providers/database/databases/sqlite-db/schemas/kv-table.js";import{BaseRepository as N}from"../../../providers/database/base-repository.js";import{createDatabaseRepositoryInstance as T}from"../../../providers/database/instance-cache-resolver.js";import{createKvValue as $}from"../mappers/create-kv-value.js";import{createKvDbRecord as D,encodeKvKey as c}from"../mappers/create-kv-db-record.js";import{decodeCursor as k}from"../helpers/decode-cursor.js";import{encodeCursor as I}from"../helpers/encode-cursor.js";import{createKvListEntry as x}from"../mappers/create-kv-list-entry.js";const O="";class v extends N{#e=!1;constructor(t){super(t)}static create(t){return T(t,"kv",v)}async sync(){if(this.isNonRemoteDatabaseMode()){this.#e||(C.warn(`KV database is currently operating in local mode: not connected to the remote database.
       All changes and data will only persist locally and will not be synced remotely.`),this.#e=!0);return}await this.databaseClient.sync()}async get(t){const n=c(t),r=await this.databaseClient.client.select().from(e).where(m(b(e.encodedKey,n),f(K(e.expiresAt),l(o`datetime(${e.expiresAt})`,o`datetime('now')`)))).get();return r?$(r):null}async getMany(t){if(t.length===0)return[];const n=t.map(d=>c(d)),r=f(K(e.expiresAt),l(o`datetime(${e.expiresAt})`,o`datetime('now')`)),a=await this.databaseClient.client.select().from(e).where(m(L(e.encodedKey,n),r)).all(),s=new Map(a.map(d=>[d.encodedKey,d]));return t.map((d,p)=>{const w=n[p],y=s.get(w);return y?x(y):null})}async list(t,n){const r=n?.limit??100,a=n?.reverse??!1,s=[],d=f(K(e.expiresAt),l(o`datetime(${e.expiresAt})`,o`datetime('now')`));if(s.push(d),"prefix"in t){const i=c(t.prefix),u="start"in t?c(t.start):i,E="end"in t?c(t.end):i+O;s.push(l(e.encodedKey,u)),s.push(g(e.encodedKey,E))}else if("start"in t&&"end"in t){const i=c(t.start),u=c(t.end);s.push(l(e.encodedKey,i)),s.push(g(e.encodedKey,u))}if(n?.cursor){const i=k(n.cursor),u=a?g(e.encodedKey,i):B(e.encodedKey,i);s.push(u)}const p=this.databaseClient.client.select().from(e),w=s.length>0?p.where(m(...s)):p,y=this.databaseClient.client.select({count:M()}).from(e),A=(await(s.length>0?y.where(m(...s)):y).get())?.count??0,h=await w.orderBy(a?R(e.encodedKey):S(e.encodedKey)).limit(r).all();return{items:h.map(i=>x(i)),total:A,cursor:A>h.length?I(h[h.length-1]?.encodedKey):null}}async set(t,n,r){const a=D({key:t,value:n,ttlInSeconds:r?.ttlInSeconds});return await this.databaseClient.client.insert(e).values(a).onConflictDoUpdate({target:[e.encodedKey],set:{value:a.value,expiresAt:a.expiresAt,updatedAt:a.updatedAt}}),x(a)}async delete(t){const n=c(t);await this.databaseClient.client.delete(e).where(b(e.encodedKey,n))}async clearExpired(){await this.databaseClient.client.delete(e).where(g(o`datetime(${e.expiresAt})`,o`datetime('now')`))}async transaction(t){return this.databaseClient.transactionsManager.transaction(async()=>t({get:async r=>this.get(r),getMany:async r=>this.getMany(r),set:async(r,a,s)=>this.set(r,a,s),delete:async r=>this.delete(r)}))}async getTotalStoredEntryBytes(){try{return await this.getTableSizeInBytes("kv")}catch(t){return C.error("Error getting total kv stored entry bytes",t),0}}async getStoredEntrySizeByEncodedKey(t){try{const n=f(K(e.expiresAt),l(o`datetime(${e.expiresAt})`,o`datetime('now')`)),r=await this.databaseClient.client.select({bytes:o`COALESCE(LENGTH(CAST(${e.encodedKey} AS BLOB)) + LENGTH(CAST(${e.value} AS BLOB)), 0)`}).from(e).where(m(b(e.encodedKey,t),n)).get();return Number(r?.bytes??0)}catch(n){return C.error("Error getting kv entry size by encoded key",n),0}}}export{O as KV_KEY_END_BOUNDARY,v as KvRepository};
