import { HoudiniClient, fetch as houdiniFetch } from '$houdini';

const API_URL = 'https://api.example.com/v1/graphql/';

export default new HoudiniClient({
	url: API_URL,
	plugins: [
		houdiniFetch(async ({ fetch, text, variables, metadata }) => {
			const headers: Record<string, string> = {
				'Content-Type': 'application/json'
			};

			// Server-side: forward cookie from metadata
			const cookie = (metadata as { cookie?: string } | undefined)?.cookie;
			if (cookie) {
				headers['Cookie'] = cookie;
			}

			const res = await fetch(API_URL, {
				method: 'POST',
				headers,
				credentials: 'include', // Client-side: include cookies automatically
				body: JSON.stringify({ query: text, variables })
			});

			return await res.json();
		})
	]
});
