/* eslint-disable no-underscore-dangle */
/* eslint-disable @typescript-eslint/naming-convention */
import { ApolloClient, InMemoryCache } from '@apollo/client';
import getUrls from 'config/urls';
import { isServer } from 'tools/common';

/** @type {import('@apollo/client').ApolloClient<NormalizedCacheObject>} */
let apolloClient;

const { URL_CRM_GRAPHQL } = getUrls();

function createApolloClient() {
  return new ApolloClient({
    ssrMode: isServer(),
    uri: URL_CRM_GRAPHQL,
    cache: new InMemoryCache(),
  });
}

export default function initializeApollo(initialState = null) {
  const _apolloClient = apolloClient ?? createApolloClient();

  // If your page has Next.js data fetching methods that use Apollo Client, the initial state
  // gets hydrated here
  if (initialState) {
    _apolloClient.cache.restore(initialState);
  }
  // For SSG and SSR always create a new Apollo Client
  if (isServer()) return _apolloClient;
  // Create the Apollo Client once in the client
  if (!apolloClient) apolloClient = _apolloClient;

  return _apolloClient;
}
