import * as Option from 'effect/Option';
import * as SchemaAST from 'effect/SchemaAST';
import { PropertyIdSymbol } from '../constants.js';
import { generateId } from '../utils/generateId.js';
import { isRelation } from '../utils/isRelation.js';
import { findOne } from './findOne.js';
import { encodeToGrc20Json } from './schema.js';
export const create = (handle, type) => {
  return data => {
    const entityId = generateId();
    const encoded = encodeToGrc20Json(type, {
      ...data,
      id: entityId
    });
    const relations = {};
    const ast = type.ast;
    for (const prop of ast.propertySignatures) {
      const result = SchemaAST.getAnnotation(PropertyIdSymbol)(prop.type);
      if (Option.isSome(result) && isRelation(prop.type)) {
        if (encoded[result.value]) {
          for (const toEntityId of encoded[result.value]) {
            const relationId = generateId();
            relations[relationId] = {
              from: entityId,
              to: toEntityId,
              fromPropertyId: result.value,
              __deleted: false
            };
          }
        }
        delete encoded[result.value];
      }
    }
    handle.change(doc => {
      doc.entities ??= {};
      doc.entities[entityId] = {
        ...encoded,
        __deleted: false
      };
      doc.relations ??= {};
      // merge relations with existing relations
      for (const [relationId, relation] of Object.entries(relations)) {
        doc.relations[relationId] = relation;
      }
    });
    return findOne(handle, type)(entityId);
  };
};
//# sourceMappingURL=create.js.map