import type { PageServerLoad } from './$types';
import { getWeekDateRange } from '$lib/utils/date';

export const load: PageServerLoad = async ({ parent }) => {
	// Get parent data - no additional queries needed!
	// The layout already fetched all month data, we just filter for this week
	const parentData = await parent();

	// Get current week's date range for filtering
	const { start, end } = getWeekDateRange();

	// Filter services and projects for this week from parent data
	const isInWeek = (date: string) => date >= start && date <= end;

	const weekServices = {
		scheduled: (parentData.services?.scheduled ?? []).filter((s) => isInWeek(s.date)),
		inProgress: (parentData.services?.inProgress ?? []).filter((s) => isInWeek(s.date))
	};

	const weekProjects = {
		scheduled: (parentData.projects?.scheduled ?? []).filter((p) => isInWeek(p.date)),
		inProgress: (parentData.projects?.inProgress ?? []).filter((p) => isInWeek(p.date))
	};

	// Filter invoices for SENT status (awaiting payment)
	const pendingInvoices = (parentData.invoices ?? []).filter((i) => i.status === 'SENT');

	return {
		...parentData,
		dashboard: {
			services: weekServices,
			projects: weekProjects,
			invoices: pendingInvoices
		}
	};
};
