import { calendarService } from '$lib/services/calendar';
import type { PageServerLoad } from './$types';

// Format date as YYYY-MM
function formatMonth(date: Date): string {
	const year = date.getFullYear();
	const month = (date.getMonth() + 1).toString().padStart(2, '0');
	return `${year}-${month}`;
}

export const load: PageServerLoad = async ({ parent, url }) => {
	// Get team profiles from parent layout
	const parentData = await parent();

	// Read month from URL params, default to current month
	const monthParam = url.searchParams.get('month');
	const now = new Date();
	let currentMonth: string;
	let timeMin: Date;
	let timeMax: Date;

	if (monthParam && /^\d{4}-\d{2}$/.test(monthParam)) {
		// Parse month param and calculate boundaries
		currentMonth = monthParam;
		const [year, month] = monthParam.split('-').map(Number);
		timeMin = new Date(year, month - 1, 1);
		timeMax = new Date(year, month, 0, 23, 59, 59, 999); // Last day of month
	} else {
		// Default: current month
		currentMonth = formatMonth(now);
		timeMin = new Date(now.getFullYear(), now.getMonth(), 1);
		timeMax = new Date(now.getFullYear(), now.getMonth() + 1, 0, 23, 59, 59, 999);
	}

	const eventsResult = await calendarService.listEvents({
		timeMin: timeMin.toISOString(),
		timeMax: timeMax.toISOString(),
		maxResults: 100
	});

	return {
		events: eventsResult.data ?? [],
		eventsError: eventsResult.error ?? null,
		teamProfiles: parentData.team?.data?.teamProfiles ?? [],
		currentMonth
	};
};
