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