import { redirect } from '@sveltejs/kit';
import type { PageServerLoad } from './$types';
import { createServerClient } from '$lib/graphql/client';
import { MY_PROFILE_QUERY, type MyProfileQueryResult } from '$lib/graphql/queries/myProfile';

export const load: PageServerLoad = async ({ locals }) => {
	// Require authentication
	if (!locals.cookie) {
		redirect(302, '/login');
	}

	const client = createServerClient(locals.cookie);

	try {
		const result = await client.query<MyProfileQueryResult>({
			query: MY_PROFILE_QUERY,
			fetchPolicy: 'network-only'
		});

		if (!result.data?.me) {
			redirect(302, '/login');
		}

		return {
			profile: result.data.me
		};
	} catch (error) {
		console.error('Failed to fetch profile:', error);
		redirect(302, '/login');
	}
};
