import { BoardClient } from '@things-shell/board-api-gql'

import { navigate, store } from '../reducer/store'
import { authError } from '../reducer/actions/actions-auth'
import ThingsSnackbar from '../components/things-snackbar'

const GRAPHQL_URI = '/graphql'
const defaultOptions = {
  watchQuery: {
    fetchPolicy: 'no-cache',
    errorPolicy: 'ignore'
  },
  query: {
    fetchPolicy: 'no-cache', //'network-only'
    errorPolicy: 'all'
  },
  mutate: {
    errorPolicy: 'all'
  }
}

const ERROR_HANDLER = ({ graphQLErrors, networkError }) => {
  if (graphQLErrors)
    graphQLErrors.map(({ message, locations, path }) => {
      console.error(`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`)
      ThingsSnackbar.toast(`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`)
    })

  if (networkError) {
    console.error(`[Network error - ${networkError.statusCode}]: ${networkError}`)
    switch (networkError.statusCode) {
      case 401:
        if (location.pathname !== '/signup') {
          store.dispatch(authError(networkError))
          store.dispatch(navigate('/signin'))
        }
        break
      default:
        ThingsSnackbar.toast(`[Network error - ${networkError.statusCode}]: ${networkError}`)
    }
  }
}

const client = new BoardClient(GRAPHQL_URI, ERROR_HANDLER, {
  defaultOptions
})

export default client
