import { useMemo } from 'react';
import type { TypedDocumentNode } from '@apollo/client';
import { type OperationDefinitionNode, print } from 'graphql';

/**
 * Approximate how long the URL will be when using a GET request for a GraphQL query.
 */
export function useGetQueryStrlen(query: TypedDocumentNode<any, any>, variables: object) {
   return useMemo(() => {
      const operationName = (query.definitions?.[0] as OperationDefinitionNode)?.name?.value;
      let asString = window.location.href;
      asString += `&query=${print(query)}`;
      asString += `&operationName=${operationName ?? ''}`;
      asString += `&variables=${encodeURIComponent(JSON.stringify(variables))}`;

      return asString.length;
   }, [variables]);
}
