import{eq as l}from"drizzle-orm";import{logger as a}from"../../../../../tools/notifiers/logger.js";import{createEntityDbRecord as p}from"../../mappers/create-entity-db-record.js";import{createEntityRelationDbRecordFromFileSchema as g}from"../../mappers/create-entity-relation-db-record-from-file-schema.js";import{entitiesTable as i}from"../../../../../providers/database/databases/catalog-sqlite/schemas/entities-table.js";import{entitiesRelationsTable as r}from"../../../../../providers/database/databases/catalog-sqlite/schemas/entities-relations-table.js";import{promiseMapLimit as f}from"../../../../../utils/async.js";import{convertFilterToWhereCondition as u}from"../../../../../providers/database/pagination/filter.js";const E=15;class K{#t;#e;#r;constructor(e,t,o){this.#t=e,this.#e=t,this.#r=o}async createEntity({entity:e,fileHash:t,sourceFile:o}){try{const n=p({entity:e,sourceFile:o,organizationId:this.#e,projectId:this.#r,source:"file",fileHash:t}),{key:c,source:s,...d}=n,y=this.#t.client.insert(i).values(n).onConflictDoUpdate({target:[i.key,i.source],set:d}),h=f(e.relations??[],E,async m=>this.createEntityRelation(g({relation:m,sourceFile:o,fileHash:t,sourceKey:e.key,organizationId:this.#e,projectId:this.#r})));await Promise.all([y,h])}catch(n){a.error("Error adding entity",n)}}async deleteEntity(e){try{return await this.#t.client.delete(i).where(l(i.key,e)),e}catch(t){return a.error("Error deleting entity",t),null}}async deleteEntities(e){try{const t=u(e);return t?(await this.#t.client.delete(i).where(t),!0):!1}catch(t){return a.error("Error deleting entities",t),!1}}async deleteEntityRelation(e){try{return await this.#t.client.delete(r).where(l(r.id,e)),e}catch{return null}}async deleteEntityRelations(e){try{const t=u(e);return t?(await this.#t.client.delete(r).where(t),!0):!1}catch(t){return a.error("Error deleting entity relations",t),!1}}async createEntityRelation(e){if(!e)return null;try{const{sourceKey:t,targetKey:o,targetToSourceRelation:n,...c}=e,s=await this.#t.client.insert(r).values(e).onConflictDoUpdate({target:[r.sourceKey,r.targetToSourceRelation,r.targetKey],set:c}).returning();return s?.length?s[0]:null}catch(t){return a.error("Error creating entity relation",t),null}}}export{K as CatalogEntitiesLocalWriteRepository};
