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

export const useUserGraphql = () => {
  const config = useRuntimeConfig()
  const teamsGraphqlUser = config.public.teamsGraphqlUser
  const auth = useAuth()

  const execute = async <TResult, TVariables>(
    document: TypedDocumentNode<TResult, TVariables>,
    variables?: TVariables
  ): Promise<TResult> => {
    const token = await auth.getIdToken()

    const response = await $fetch<{ data: TResult; errors?: Array<{ message: string }> }>(
      teamsGraphqlUser,
      {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          ...(token ? { Authorization: `Bearer ${token}` } : {}),
        },
        body: {
          query: print(document),
          variables: variables || {},
        },
      }
    )

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

    return response.data
  }

  return { execute }
}
