'use client';

import { ApolloClient, HttpLink, InMemoryCache, from } from '@apollo/client';
import { setContext } from '@apollo/client/link/context';
import { getSession } from 'next-auth/react';

function graphqlUri(): string {
  const configured = process.env.NEXT_PUBLIC_GRAPHQL_ENDPOINT || '';
  if (configured.startsWith('/')) {
    if (typeof window !== 'undefined') return configured;
    const base =
      process.env.SANKOFA_PHOENIX_API_INTERNAL_URL ||
      process.env.NEXT_PUBLIC_PHOENIX_API_INTERNAL_URL ||
      'http://192.168.11.50:8080';
    return `${base.replace(/\/$/, '')}${configured}`;
  }
  return configured || 'http://localhost:4000/graphql';
}

export function createApolloClient() {
  const authLink = setContext(async (_, { headers }) => {
    const session = await getSession();
    const token = session?.accessToken;
    const tenantId = session?.tenantId;
    return {
      headers: {
        ...headers,
        ...(token ? { Authorization: `Bearer ${token}` } : {}),
        ...(tenantId ? { 'X-Tenant-Id': tenantId } : {}),
      },
    };
  });

  const httpLink = new HttpLink({
    uri: graphqlUri(),
    credentials: 'include',
  });

  return new ApolloClient({
    cache: new InMemoryCache(),
    link: from([authLink, httpLink]),
    defaultOptions: {
      watchQuery: { fetchPolicy: 'cache-and-network', errorPolicy: 'all' },
      query: { errorPolicy: 'all' },
    },
  });
}
