import { GraphQLClient } from 'graphql-request'

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

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

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

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

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

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

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

  return res
}
