import { Graph, Id } from '@graphprotocol/grc-20';
import { store, Type } from '@graphprotocol/hypergraph';
import { useQueryClient } from '@tanstack/react-query';
import { useSelector } from '@xstate/store/react';
import { publishOps } from '../publish-ops.js';
export function useCreateEntityPublic(type, {
  space
}) {
  const mapping = useSelector(store, state => state.context.mapping);
  const queryClient = useQueryClient();
  return async (data, {
    walletClient
  }) => {
    try {
      // @ts-expect-error TODO should use the actual type instead of the name in the mapping
      const typeName = type.name;
      const mappingEntry = mapping?.[typeName];
      if (!mappingEntry) {
        throw new Error(`Mapping entry for ${typeName} not found`);
      }
      const fields = type.fields;
      const values = [];
      for (const [key, value] of Object.entries(mappingEntry.properties || {})) {
        let serializedValue = data[key];
        if (fields[key] === Type.Checkbox) {
          serializedValue = Graph.serializeCheckbox(data[key]);
        } else if (fields[key] === Type.Date) {
          serializedValue = Graph.serializeDate(data[key]);
        } else if (fields[key] === Type.Point) {
          serializedValue = Graph.serializePoint(data[key]);
        } else if (fields[key] === Type.Number) {
          serializedValue = Graph.serializeNumber(data[key]);
        }
        values.push({
          property: Id.Id(value),
          value: serializedValue
        });
      }
      const relations = {};
      for (const [key, relationId] of Object.entries(mappingEntry.relations || {})) {
        const toIds = [];
        if (data[key]) {
          // @ts-expect-error - TODO: fix the types error
          for (const entity of data[key]) {
            if (typeof entity === 'string') {
              toIds.push({
                toEntity: Id.Id(entity)
              });
            } else {
              toIds.push({
                toEntity: Id.Id(entity.id)
              });
            }
          }
          relations[Id.Id(relationId)] = toIds;
        }
      }
      const {
        ops
      } = Graph.createEntity({
        types: mappingEntry.typeIds,
        id: data.id,
        values,
        relations
      });
      const {
        cid,
        txResult
      } = await publishOps({
        ops,
        space,
        name: `Create entity ${data.id}`,
        walletClient
      });
      // TODO: temporary fix until we get the information from the API when a transaction is confirmed
      await new Promise(resolve => setTimeout(resolve, 2000));
      queryClient.invalidateQueries({
        queryKey: ['hypergraph-public-entities',
        // @ts-expect-error - TODO: find a better way to access the type.name
        type.name, space]
      });
      return {
        success: true,
        cid,
        txResult
      };
    } catch (error) {
      console.error(error);
      return {
        success: false,
        error: 'Failed to create entity'
      };
    }
  };
}
//# sourceMappingURL=use-create-entity-public.js.map