/* eslint-disable no-underscore-dangle */
/* eslint-disable @typescript-eslint/naming-convention */
import { ApolloClient, InMemoryCache } from '@apollo/client';

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

// prettier-ignore
const uri = typeof window === 'undefined'
    ? process.env.NEXT_PUBLIC_URL_CRM_GRAPHQL_DIRECT
    : process.env.NEXT_PUBLIC_URL_CRM_GRAPHQL_PROXY;

function createApolloClient() {
  return new ApolloClient({
    ssrMode: typeof window === 'undefined',
    uri,
    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 (typeof window === 'undefined') return _apolloClient;
  // Create the Apollo Client once in the client
  if (!apolloClient) apolloClient = _apolloClient;

  return _apolloClient;
}
