import type { PageServerLoad } from './$types';
import { createServerClient } from '$lib/graphql/client';
import { RECENT_EVENTS_QUERY, type RecentEventsQueryResult } from '$lib/graphql/queries/events';
import { redirect } from '@sveltejs/kit';

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

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

	if (!locals.cookie) {
		return {
			events: [],
			limit: 100,
			offset: 0
		};
	}

	const limit = parseInt(url.searchParams.get('limit') ?? '100');
	const offset = parseInt(url.searchParams.get('offset') ?? '0');

	const client = createServerClient(locals.cookie);

	try {
		const result = await client.query<RecentEventsQueryResult>({
			query: RECENT_EVENTS_QUERY,
			variables: { limit, offset }
		});

		return {
			events: result.data?.recentEvents ?? [],
			limit,
			offset
		};
	} catch (err) {
		console.error('Failed to fetch events:', err);
		return {
			events: [],
			limit,
			offset
		};
	}
};
