import { GraphQLClient } from 'graphql-request'

type Options = {
  headers: {
    'Content-Type': string
    Authorization?: string
  }
}

export default async function fetchQueryAPI(query: string, { variables = {} }: Record<string, any> = {}) {
  if (!process.env.NEXT_PUBLIC_ATLAS_SEARCH_URL) {
    console.error('Environment variable missing: NEXT_PUBLIC_ATLAS_SEARCH_URL')
    throw new Error('Environment variable missing: NEXT_PUBLIC_ATLAS_SEARCH_URL')
  }

  const options: Options = { headers: { 'Content-Type': 'application/json' } }

  if (process.env.ATLAS_SEARCH_ACCESS_TOKEN) {
    options.headers['Authorization'] = `${process.env.ATLAS_SEARCH_ACCESS_TOKEN}`
  }

  const graphQLClient = new GraphQLClient(`${process.env.NEXT_PUBLIC_ATLAS_SEARCH_URL}` || '', options)

  const res = await graphQLClient.request(query, variables)

  if (res.errors) {
    console.error(res.errors)
    throw new Error('Failed to fetch API')
  }

  return res
}
