import { ApolloClient, InMemoryCache, HttpLink } from '@apollo/client/core';
import UploadHttpLink from 'apollo-upload-client/UploadHttpLink.mjs';
import { browser } from '$app/environment';
import { config } from '$lib/config';

// Upload link for browser requests - supports file uploads + regular queries
// Uses GraphQL multipart request spec for file uploads
const uploadLink = new UploadHttpLink({
	uri: config.graphql.url,
	credentials: 'include'
});

// Browser client - used for client-side queries and mutations (including uploads)
export const client = new ApolloClient({
	link: uploadLink,
	cache: new InMemoryCache(),
	ssrMode: !browser
});

// Server client factory - creates a client with cookie header for SSR
// Note: Server-side doesn't need upload support, uses regular HttpLink
export function createServerClient(cookie: string | null) {
	const serverHttpLink = new HttpLink({
		uri: config.graphql.url,
		headers: cookie ? { Cookie: cookie } : {}
	});

	return new ApolloClient({
		link: serverHttpLink,
		cache: new InMemoryCache(),
		ssrMode: true
	});
}
