import type { TypedDocumentNode } from '@graphql-typed-document-node/core'
import { print } from 'graphql'

export const usePublicGraphql = () => {
  const config = useRuntimeConfig()
  const exchangeGraphqlPublic = config.public.exchangeGraphqlPublic

  const execute = async <TResult, TVariables>(
    document: TypedDocumentNode<TResult, TVariables>,
    variables?: TVariables
  ): Promise<TResult> => {
    const response = await $fetch<{ data: TResult; errors?: Array<{ message: string }> }>(
      exchangeGraphqlPublic,
      {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: {
          query: print(document),
          variables: variables || {},
        },
      }
    )

    if (response.errors?.length) {
      throw new Error(response.errors[0]?.message || 'GraphQL error')
    }

    return response.data
  }

  return { execute }
}
