import { ApolloClient, InMemoryCache, ApolloLink } from '@apollo/client';
import { createUploadLink }  from 'apollo-upload-client';
import { setContext } from '@apollo/client/link/context';
import { onError } from '@apollo/client/link/error';

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

const uploadLink = createUploadLink({
  uri: process.env.REACT_APP_API_URL,
});

// Handle expired/invalid session and network 403s
const errorLink = onError(({ graphQLErrors, networkError }) => {
  if (graphQLErrors) {
    for (const err of graphQLErrors) {
      const code = (err.extensions as any)?.code;
      const message = err.message || '';
      if (code === 'UNAUTHENTICATED' || message.includes('403')) {
        try { alert('Your session has expired. Please log in again.'); } catch {}
        try {
          localStorage.removeItem('token');
          localStorage.removeItem('user');
          sessionStorage.setItem('isLoggedIn', 'false');
        } catch {}
        if (typeof window !== 'undefined') {
          window.location.href = '/';
        }
        return;
      }
    }
  }

  if (networkError) {
    const msg = (networkError as any).message || '';
    if (msg.includes('status code 403') || msg.includes('403') || msg.toLowerCase().includes('expired token')) {
      try { alert('Your session has expired. Please log in again.'); } catch {}
      try {
        localStorage.removeItem('token');
        localStorage.removeItem('user');
        sessionStorage.setItem('isLoggedIn', 'false');
      } catch {}
      if (typeof window !== 'undefined') {
        window.location.href = '/';
      }
    }
    // eslint-disable-next-line no-console
    console.error(`[Network error]: ${msg}`);
  }
});

export const client = new ApolloClient({
  link: ApolloLink.from([authLink, errorLink, uploadLink]),
  cache: new InMemoryCache(),
});
