import type { LayoutServerLoad } from './$types';
import { redirect, error } from '@sveltejs/kit';
import { TeamDashboardStore } from '$houdini';
import { getCurrentMonth } from '$lib/utils/date';

export const load: LayoutServerLoad = async (event) => {
	const { url, parent, locals, depends } = event;

	// Register dependency for invalidation
	depends('app:dashboard');

	const parentData = await parent();
	const me = parentData.user?.data?.me;

	// Not authenticated
	if (!me) {
		const returnTo = encodeURIComponent(url.pathname + url.search);
		throw redirect(307, `/login?return_to=${returnTo}`);
	}

	// Team routes require team profile (any role: admin, team_leader, team_member)
	if (me.__typename !== 'TeamProfileType') {
		throw error(403, 'This area is only accessible to team members');
	}

	// Get month from query params or use current month
	const month = url.searchParams.get('month') || getCurrentMonth();
	const fetchParams = { event, metadata: { cookie: locals.cookie } };

	// Single consolidated query for all team dashboard data
	const dashboardResult = await new TeamDashboardStore().fetch({
		...fetchParams,
		variables: { teamProfileId: me.id, month }
	});

	const dashboard = dashboardResult.data?.teamDashboard;

	// Filter services and projects by status client-side
	const services = dashboard?.services ?? [];
	const projects = dashboard?.projects ?? [];

	return {
		...parentData,
		services: {
			scheduled: services.filter((s) => s.status === 'SCHEDULED'),
			inProgress: services.filter((s) => s.status === 'IN_PROGRESS'),
			completed: services.filter((s) => s.status === 'COMPLETED')
		},
		projects: {
			scheduled: projects.filter((p) => p.status === 'SCHEDULED'),
			inProgress: projects.filter((p) => p.status === 'IN_PROGRESS'),
			completed: projects.filter((p) => p.status === 'COMPLETED')
		},
		reports: dashboard?.reports ?? [],
		filters: { month }
	};
};
