import{logger as i}from"../../../../tools/notifiers/logger.js";import{relatedEntityDatabaseSchema as y,relatedEntityQueryRowDatabaseSchema as s}from"../../schemas/database-schemas.js";import{validateWithResult as o}from"../../utils/ajv-validator.js";import{readString as t}from"../../utils/read-string.js";function u(e){return!e.id||!e.type||!e.key||!e.title?(i.warn(`Invalid database bff catalog related entity: missing required fields (id: ${e.id}, type: ${e.type}, key: ${e.key}, title: ${e.title})`),null):{id:e.id,type:e.type,key:e.key,title:e.title,summary:e.summary,source:e.source,sourceFile:e.sourceFile,relationRole:e.relationRole,relationType:e.relationType,createdAt:e.createdAt,updatedAt:e.updatedAt,metadata:e.metadata,version:e.version,...e.revision!==null&&{revision:e.revision}}}function l(e){if(e){if(typeof e=="string")try{return e?JSON.parse(e):void 0}catch{return}if(typeof e=="object"&&e!==null)return e}}function p(e){return typeof e=="string"||e===null||typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null}function m(e){const a=t(e.source_to_target_relation)??t(e.target_to_source_relation)??t(e.relationType)??t(e.relation_type)??t(e.relationName)??t(e.relation_name)??"";return{id:t(e.id)??"",type:t(e.type)??"",key:t(e.key)??"",title:t(e.title)??"",summary:t(e.summary,!0)??null,source:t(e.source)??"",source_file:t(e.source_file,!0)??t(e.sourceFile,!0)??null,direction:t(e.direction)??"",relation_field:a,created_at:t(e.created_at,!0)??t(e.createdAt,!0)??"",updated_at:t(e.updated_at,!0)??t(e.updatedAt,!0)??"",metadata:p(e.metadata),version:t(e.version,!0)??null,revision:t(e.revision,!0)??null}}function k(e){const a=o(y,e);if(!a.success)return i.warn(`Invalid database bff catalog related entity, error: ${a.error}`),null;const r=a.data||{};return u({id:r.id,type:r.type,key:r.key,title:r.title,summary:r.summary||null,source:r.source,sourceFile:r.source_file||null,relationRole:r.relation_role||"source",relationType:r.relation_type||"",createdAt:r.created_at,updatedAt:r.updated_at,metadata:l(r.metadata),version:r.version||null,revision:null})}function R(e){const a=m(e),r=o(s,a);if(!r.success)return i.warn(`Invalid database bff catalog related entity query row (key: ${a.key||"unknown"}), error: ${r.error}`),null;const n=r.data||{},c=n.direction==="outgoing"?"source":"target",d=n.relation_field.replace("reverse:","");return u({id:n.id,type:n.type,key:n.key,title:n.title,summary:n.summary??null,source:n.source,sourceFile:n.source_file??null,relationRole:c,relationType:d,createdAt:n.created_at,updatedAt:n.updated_at,metadata:l(n.metadata),version:n.version??null,revision:n.revision??null})}export{k as createBffRelatedEntity,R as createBffRelatedEntityFromQueryRow};
