import{and as i,eq as a}from"drizzle-orm";import{isTtlExpired as m}from"../../../utils/is-ttl-expired.js";import{logger as n}from"../../../tools/notifiers/logger.js";import{cacheTable as r}from"../../../providers/database/databases/sqlite-db/schemas/cache-table.js";import{createDatabaseRepositoryInstance as d,InstanceCacheResolver as h}from"../../../providers/database/instance-cache-resolver.js";import{createCacheDbRecord as u}from"../mappers/create-cache-db-record.js";import{createCacheReadModel as p}from"../mappers/create-cache-read-model.js";class l{static#t=new h(e=>d(e,"cache",l));#e;constructor(e){this.#e=e.client}static async getInstance(e){return l.#t.get(e)}async get(e,t){const c=[a(r.key,e)];t&&c.push(a(r.namespace,t));const o=await this.#e.client.select().from(r).where(i(...c)).get();if(!o)return null;const s=p(o);return m(s.ttlInSeconds,s.createdAt)?(await this.delete(e,t),null):s}async set(e){try{const t=u(e);return await this.#e.client.insert(r).values(t).onConflictDoUpdate({target:[r.key],set:{value:t.value,namespace:t.namespace,ttl:t.ttl,updatedAt:t.updatedAt}}),t.key}catch(t){return n.error("Error setting cache: "+t.message),null}}async delete(e,t){try{return await this.#e.client.delete(r).where(i(a(r.key,e),a(r.namespace,t))),!0}catch(c){return n.error("Error deleting cache: "+c.message),!1}}async deleteByNamespace(e){try{return await this.#e.client.delete(r).where(a(r.namespace,e)),!0}catch(t){return n.error("Error deleting cache by namespace: "+t.message),!1}}async clearAll(){try{return await this.#e.client.delete(r),!0}catch(e){return n.error("Error clearing all cache: "+e.message),!1}}}export{l as CacheRepository};
