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

type TeamEndpoint = 'teams' | 'orders' | 'kyc' | 'exchange'

export const useTeamGraphql = () => {
  const config = useRuntimeConfig()
  const auth = useAuth()

  const endpoints: Record<TeamEndpoint, string> = {
    teams: config.public.teamsGraphqlTeam,
    orders: config.public.ordersGraphqlTeam,
    kyc: config.public.kycGraphqlTeam,
    exchange: config.public.exchangeGraphqlTeam,
  }

  const execute = async <TResult, TVariables>(
    endpoint: TeamEndpoint,
    document: TypedDocumentNode<TResult, TVariables>,
    variables?: TVariables
  ): Promise<TResult> => {
    const token = await auth.getAccessToken()
    const url = endpoints[endpoint]

    if (!url) {
      throw new Error(`Unknown team endpoint: ${endpoint}`)
    }

    const response = await $fetch<{ data: TResult; errors?: Array<{ message: string }> }>(
      url,
      {
        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 }
}
