import{envConfig as a}from"../../config/env-config.js";import{logger as n}from"../../tools/notifiers/logger.js";import{SQLD_REMOTE_DATABASE_URL_NO_DEPLOYMENT_YET_VAR as p}from"../../constants/plugins/catalog-entities.js";import{HTTP_TRANSIENT_RETRY as o,describeTransientError as c,isTransientSqldError as R,withTransientErrorRetry as s}from"./transient-sqld-error.js";class w{#i;#r;#o=null;#s;constructor(t,r){this.#i=t,this.#r=l(t)==="local",this.#o=r.repository,this.#s=r.createRepository}get isLocalDbMode(){return this.#r}getRepository(){return this.#o}setRepository(t){this.#o=t}async recreateRepository(){return!this.#s||!this.#i?null:this.#s(this.#i)}async syncRepositoryIfNeeded(){if(this.#r)return;const t=this.getRepository();t&&await s(()=>t.sync(),o)}async runRead(t,r){if(r?.skipSync||await this.syncRepositoryIfNeeded(),this.#r)try{return await this.#t(t,r)}catch(e){throw this.#e("read",e),e}try{return await s(()=>this.#t(t,r),o)}catch(e){throw this.#e("read",e),e}}async runWrite(t,r){if(this.#r)try{return await this.#t(t,r)}catch(e){throw this.#e("write",e),e}try{return await s(async()=>{try{return await this.#t(t,r)}catch(e){throw await this.#a(e),e}},o)}catch(e){throw this.#e("write",e),e}}async#t(t,r){const e=this.getRepository();if(!e){if(r?.onRepositoryMissing)return await r.onRepositoryMissing();throw new Error("Database repository is not initialized")}return t(e)}async#a(t){if(R(t))try{const r=await this.recreateRepository();r&&this.setRepository(r)}catch(r){n.warn(`Reconnect attempt failed, letting original error propagate: ${c(r)}`)}}#e(t,r){const e=this.constructor.name,h=r instanceof Error?c(r):String(r),y=this.#r?"local-no-retry":"remote-retry-enabled";n.error(`[${e}] ${t} operation failed (${y}): ${h}`,r)}}function l(i){if(i?.databaseType)return i.databaseType;const t=a.SQLD_REMOTE_DATABASE_URL||i?.sqldRemoteDatabaseUrl,r=a.SQLD_REMOTE_DATABASE_AUTH_TOKEN||i?.sqldRemoteDatabaseAuthToken;return t&&t!==p&&r?"remote":"local"}export{w as BaseService};
