import{and as a,eq as i,ne as d,or as u,sql as g}from"drizzle-orm";import{entitiesRelationsTable as t}from"../../../../../providers/database/databases/sqlite-db/schemas/entities-relations-table.js";import{logger as c}from"../../../../../tools/notifiers/logger.js";import{entitiesTable as o}from"../../../../../providers/database/databases/sqlite-db/schemas/entities-table.js";import{promiseMapLimit as f}from"../../../../../utils/async/promise-map-limit.js";import{convertFilterToWhereCondition as v}from"../../../../../providers/database/pagination/filter.js";import{createEntityRelationReadModel as p}from"../../mappers/create-entity-relation-read-model.js";import{createEntityRelationDbRecordFromDto as w}from"../../mappers/create-entity-relation-db-record-from-dto.js";const E=15;class U{#e;#t;#r;constructor(r,e,n){this.#e=r,this.#t=e,this.#r=n}async createEntityRelation(r){try{const e=w(r,this.#t,this.#r),n=await this.upsertEntityRelation(e);return p(n)}catch(e){throw c.error("Error creating entity relation",e),e}}async createEntityRelations(r){return await f(r,E,async e=>this.createEntityRelation(e))}async upsertEntityRelation(r){if(!r)return null;try{const{sourceKey:e,targetKey:n,sourceVersion:h,targetVersion:s,sourceRevision:l,targetRevision:m,...R}=r,y=await this.#e.client.insert(t).values(r).onConflictDoUpdate({target:[t.sourceKey,t.targetKey,t.sourceVersion,t.targetVersion,t.sourceRevision,t.targetRevision,t.sourceToTargetRelation],set:R}).returning();return y?.length?y[0]:null}catch(e){return c.error("Error creating entity relation",e),null}}async deleteEntityRelation(r){try{return await this.#e.client.delete(t).where(i(t.id,r)),r}catch(e){return c.error("Error deleting entity relation",e),null}}async deleteEntitiesRelations(r){try{const e=v(r);return e?(await this.#e.client.delete(t).where(e),!0):!1}catch(e){return c.error("Error deleting entities relations",e),!1}}async deleteEntityRelationsOnEntityRemoval(r){const{key:e,version:n,revision:h}=r,s=n??"",l=h??"";if(((await this.#e.client.select({count:g`COUNT(*)`}).from(o).where(a(i(o.key,e),d(o.id,r.id))).get())?.count??0)===0){await this.#e.client.delete(t).where(u(i(t.sourceKey,e),i(t.targetKey,e)));return}if(((await this.#e.client.select({count:g`COUNT(*)`}).from(o).where(a(i(o.key,e),i(o.version,s),d(o.id,r.id))).get())?.count??0)===0){await this.#e.client.delete(t).where(u(a(i(t.sourceKey,e),i(t.sourceVersion,s)),a(i(t.targetKey,e),i(t.targetVersion,s))));return}await this.#e.client.delete(t).where(u(a(i(t.sourceKey,e),i(t.sourceVersion,s),i(t.sourceRevision,l)),a(i(t.targetKey,e),i(t.targetVersion,s),i(t.targetRevision,l))))}}export{U as RelationsWriteRepository};
