import {
  ApolloClient,
  InMemoryCache,
  ServerParseError,
  split,
} from "@apollo/client";
import { BatchHttpLink as HttpLink } from "@apollo/client/link/batch-http";
import { setContext } from "@apollo/client/link/context";
import { onError } from "@apollo/client/link/error";
import { getMainDefinition } from "@apollo/client/utilities";

import { config } from "./config";

const errorLink = onError(({ networkError }) => {
  if (networkError) {
    const { statusCode } = networkError as ServerParseError;
    if (statusCode === 401) {
      localStorage.removeItem(config.localstorageKeys.token);
    }
  }
});

const authLink = setContext((_, { headers }) => {
  const token = localStorage.getItem(config.localstorageKeys.token);
  console.log(token);
  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : "",
    },
  };
});

const httpLink = new HttpLink({
  uri: `${config.api.url}/graphql`,
});

export const apolloClient = new ApolloClient({
  uri: `${config.api.url}/graphql`,
  link: authLink.concat(errorLink).concat(httpLink),
  // connectToDevTools: true,
  cache: new InMemoryCache(),
});
