import type { PageServerLoad } from './$types';
import { createServerClient } from '$lib/graphql/client';
import { CALENDAR_EVENT_QUERY, type CalendarEventQueryResult } from '$lib/graphql/queries/calendar';
import { redirect, error } from '@sveltejs/kit';

export const load: PageServerLoad = async ({ locals, parent, params }) => {
	const { user } = await parent();

	// Redirect if not authenticated or not an admin/team leader
	if (
		!user ||
		user.__typename !== 'TeamProfileType' ||
		(user.role !== 'ADMIN' && user.role !== 'TEAM_LEADER')
	) {
		throw redirect(303, '/');
	}

	if (!locals.cookie) {
		throw error(401, 'Not authenticated');
	}

	const client = createServerClient(locals.cookie);

	try {
		const result = await client.query<CalendarEventQueryResult>({
			query: CALENDAR_EVENT_QUERY,
			variables: {
				eventId: params.event
			}
		});

		if (!result.data?.calendarEvent) {
			throw error(404, 'Event not found');
		}

		return {
			event: result.data.calendarEvent
		};
	} catch (err) {
		console.error('Failed to fetch calendar event:', err);
		throw error(500, 'Failed to load calendar event');
	}
};
