import { Graph } from '@graphprotocol/grc-20';
import { Constants, Utils } from '@graphprotocol/hypergraph';
import * as Option from 'effect/Option';
import * as SchemaAST from 'effect/SchemaAST';
import { request } from 'graphql-request';
import { buildRelationsSelection } from '../utils/relation-query-helpers.js';
import { parseResult } from './find-many-public.js';
const buildSearchQuery = (relationInfoLevel1, includeSpaceIds) => {
  const relationsSelection = buildRelationsSelection(relationInfoLevel1, 'single');
  const spaceIdsSelection = includeSpaceIds ? '\n    spaceIds' : '';
  return `
query searchEntities($query: String!, $spaceId: UUID!, $typeIds: [UUID!]!, $first: Int, $filter: EntityFilter!, $offset: Int) {
  entities: search(
    query: $query
    filter: { and: [{
      typeIds: {in: $typeIds}, 
      spaceIds: {in: [$spaceId]},
    }, $filter]}
    spaceId: $spaceId
    first: $first
    offset: $offset
  ) {
    id
    name${spaceIdsSelection}
    valuesList(filter: {spaceId: {is: $spaceId}}) {
      propertyId
      string
      boolean
      number
      time
      point
    }
    ${relationsSelection}
  }
}`;
};
export const searchManyPublic = async (type, params) => {
  const {
    query,
    filter,
    include,
    space,
    first = 100,
    offset = 0,
    includeSpaceIds: includeSpaceIdsParam
  } = params ?? {};
  const includeSpaceIds = includeSpaceIdsParam ?? false;
  // constructing the relation type ids for the query
  const relationTypeIds = Utils.getRelationTypeIds(type, include);
  const typeIds = SchemaAST.getAnnotation(Constants.TypeIdsSymbol)(type.ast).pipe(Option.getOrElse(() => []));
  const queryDocument = buildSearchQuery(relationTypeIds, includeSpaceIds);
  const filterParams = filter ? Utils.translateFilterToGraphql(filter, type) : {};
  const result = await request(`${Graph.TESTNET_API_ORIGIN}/graphql`, queryDocument, {
    spaceId: space,
    typeIds,
    query,
    first,
    filter: filterParams,
    offset
  });
  const {
    data,
    invalidEntities,
    invalidRelationEntities
  } = parseResult(result, type, relationTypeIds, includeSpaceIdsParam === undefined ? undefined : {
    includeSpaceIds: includeSpaceIdsParam
  });
  return {
    data,
    invalidEntities,
    invalidRelationEntities
  };
};
//# sourceMappingURL=search-many-public.js.map