import type { LayoutServerLoad } from './$types';
import { createServerClient } from '$lib/graphql/client';
import { ME_QUERY, type MeQueryResult } from '$lib/graphql/queries/me';
import { TEAM_PROFILES_QUERY, type TeamProfilesQueryResult } from '$lib/graphql/queries/team';

export const load: LayoutServerLoad = async ({ locals }) => {
	// If no cookie, user is not authenticated
	if (!locals.cookie) {
		return { user: null, teamProfiles: [] };
	}

	const client = createServerClient(locals.cookie);

	try {
		const [meResult, teamResult] = await Promise.all([
			client.query<MeQueryResult>({ query: ME_QUERY }),
			client.query<TeamProfilesQueryResult>({ query: TEAM_PROFILES_QUERY })
		]);

		return {
			user: meResult.data?.me ?? null,
			teamProfiles: teamResult.data?.teamProfiles ?? []
		};
	} catch (error) {
		console.error('Failed to fetch user or team profiles:', error);
		return { user: null, teamProfiles: [] };
	}
};
