import Vue from 'vue'
import VueApollo from 'vue-apollo'
import Cookies from 'js-cookie'
import { ApolloClient } from 'apollo-client'
import { createUploadLink } from 'apollo-upload-client'
import { InMemoryCache } from 'apollo-cache-inmemory'
import { setContext } from 'apollo-link-context'

Vue.use(VueApollo)

const httpLink = createUploadLink({
  uri: process.env.VUE_APP_SHIPNITY_API,
  credentials: 'include'
})
const authLink = setContext(({ headers }) => {
  const token = Cookies.get('CSRF-TOKEN')
  return {
    headers: {
      ...headers,
      'X-CSRF-Token': token || null
    }
  }
})
export const apolloClient = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache()
})
const apollo = new VueApollo({
  defaultClient: apolloClient,
  errorHandler (error) {
    console.error(`ไม่สามารถเชื่อมต่อกับเซิฟเวอร์ได้ (${error.message})`)
  }
})

export default apollo
