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

function getCurrentMonth(): string {
	const now = new Date();
	const year = now.getFullYear();
	const month = String(now.getMonth() + 1).padStart(2, '0');
	return `${year}-${month}`;
}

function getMonthDateRange(month: string): { timeMin: string; timeMax: string } {
	const [year, monthNum] = month.split('-').map(Number);
	const firstDay = new Date(year, monthNum - 1, 1);
	const lastDay = new Date(year, monthNum, 0, 23, 59, 59, 999);

	return {
		timeMin: firstDay.toISOString(),
		timeMax: lastDay.toISOString()
	};
}

export const load: PageServerLoad = async ({ locals, parent, url }) => {
	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, '/');
	}

	// Parse URL parameters
	const month = url.searchParams.get('month') || getCurrentMonth();
	const { timeMin, timeMax } = getMonthDateRange(month);

	if (!locals.cookie) {
		return {
			events: [],
			month,
			error: null
		};
	}

	const client = createServerClient(locals.cookie);

	try {
		const result = await client.query<CalendarEventsQueryResult>({
			query: CALENDAR_EVENTS_QUERY,
			variables: {
				filter: {
					timeMin,
					timeMax,
					maxResults: 100
				}
			}
		});

		return {
			events: result.data?.calendarEvents ?? [],
			month,
			error: null
		};
	} catch (err) {
		console.error('Failed to fetch calendar events:', err);
		return {
			events: [],
			month,
			error: err instanceof Error ? err.message : 'Failed to load calendar events'
		};
	}
};
