import{eq as u}from"drizzle-orm";import{convertFilterToWhereCondition as A}from"../../../../../providers/database/pagination/filter.js";import{promiseMapLimit as f}from"../../../../../utils/async.js";import{logger as r}from"../../../../../tools/notifiers/logger.js";import{createEntityDbRecord as E}from"../../mappers/create-entity-db-record.js";import{createEntityReadModel as y}from"../../mappers/create-entity-read-model.js";import{createEntityRelationDbRecordFromDto as p}from"../../mappers/create-entity-relation-db-record-from-dto.js";import{entitiesTable as n}from"../../../../../providers/database/databases/catalog-sqlite/schemas/entities-table.js";import{entitiesRelationsTable as i}from"../../../../../providers/database/databases/catalog-sqlite/schemas/entities-relations-table.js";import{BaseRepository as m}from"../../../../../providers/database/base-repository.js";import{DatabaseConnectionsManager as h}from"../../../../../providers/database/database-connections-manager.js";import{CATALOG_DATABASE_MIGRATIONS_FOLDER as g,CATALOG_REMOTE_DATABASE_FOLDER as T,CATALOG_REMOTE_DATABASE_NAME as D}from"../../consts.js";import{RemoteDatabaseInitializationStrategy as _}from"../../../../../providers/database/database-initialization-strategy.js";const R=15;class o extends m{static#e;get transactionsManager(){return this.databaseClient.transactionsManager}constructor(t){super(t)}static async getInstance(t){if(!o.#e){if(!process.env.SQLD_REMOTE_DATABASE_URL||!process.env.SQLD_REMOTE_DATABASE_AUTH_TOKEN){r.warn("SQLD_REMOTE_DATABASE_URL and SQLD_REMOTE_DATABASE_AUTH_TOKEN env variables not set - remote database will not be initialized");return}try{const e=await h.getConnection({config:{...t,databaseName:D,additionalFolder:T,migrationsFolder:g,syncUrl:process.env.SQLD_REMOTE_DATABASE_URL,authToken:process.env.SQLD_REMOTE_DATABASE_AUTH_TOKEN},strategy:new _});if(!e){r.warn("Remote database connection failed"),o.#e=void 0;return}o.#e=new o(e)}catch{o.#e=void 0;return}}return o.#e}async createEntity(t){try{r.info(`Adding entity ${t.key} to remote database`);const e=E({entity:t,organizationId:this.organizationId,projectId:this.projectId,source:"remote",sourceFile:null,fileHash:null}),{key:l,source:d,...c}=e,a=await this.databaseClient.client.insert(n).values(e).onConflictDoUpdate({target:[n.key,n.source],set:c}).returning();return a.length?(t.relations&&await this.createEntityRelations(t.relations.map(s=>({...s,sourceKey:t.key,targetKey:s.key}))),y(a[0])):null}catch(e){throw r.error("Error adding entity",e),e}}async updateEntity(t){try{r.info(`Updating entity ${t.key} in remote database`);const e=E({entity:t,organizationId:this.organizationId,projectId:this.projectId,source:"remote",sourceFile:null,fileHash:null}),{key:l,source:d,...c}=e,a=await this.databaseClient.client.insert(n).values(e).onConflictDoUpdate({target:[n.key,n.source],set:c}).returning();return a.length?y(a[0]):null}catch(e){return r.error("Error updating entity",e),null}}async deleteEntity(t){try{return await this.databaseClient.client.delete(n).where(u(n.key,t)),t}catch(e){return r.error("Error deleting entity",e),null}}async createEntityRelations(t){return await f(t,R,async e=>this.createEntityRelation(e))}async createEntityRelation(t){if(!t)return null;try{const e=p(t,this.organizationId,this.projectId),{sourceKey:l,targetKey:d,targetToSourceRelation:c,...a}=e,s=await this.databaseClient.client.insert(i).values(e).onConflictDoUpdate({target:[i.sourceKey,i.targetToSourceRelation,i.targetKey],set:a}).returning();return s.length?s[0]:null}catch(e){throw r.error("Error creating entity relation",e),e}}async deleteEntityRelation(t){try{return await this.databaseClient.client.delete(i).where(u(i.id,t)),t}catch(e){return r.error("Error deleting entity relation",e),null}}async deleteEntitiesRelations(t){try{const e=A(t);return e?(await this.databaseClient.client.delete(i).where(e),!0):!1}catch(e){return r.error("Error deleting entities relations",e),!1}}}export{o as CatalogEntitiesRemoteRepository};
