import type { LayoutServerLoad } from './$types';
import { redirect, error } from '@sveltejs/kit';
import { AdminDashboardStore, AccountsStore } 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}`);
	}

	// Admin requires team profile with admin or team_leader role
	if (me.__typename !== 'TeamProfileType') {
		throw error(403, 'Admin access requires a team profile');
	}

	if (me.role !== 'ADMIN' && me.role !== 'TEAM_LEADER') {
		throw error(403, 'Admin access requires an admin or team leader role');
	}

	const fetchParams = { event, metadata: { cookie: locals.cookie } };

	// Get month from URL params or default to current
	const month = url.searchParams.get('month') ?? getCurrentMonth();

	// Fetch dashboard data and full accounts in parallel
	// Admin pages need full account data with schedules, scopes, contacts, revenues
	const [dashboardResult, accountsResult] = await Promise.all([
		new AdminDashboardStore().fetch({
			...fetchParams,
			variables: { month }
		}),
		new AccountsStore().fetch(fetchParams)
	]);

	const dashboard = dashboardResult.data?.adminDashboard;

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

	return {
		...parentData,
		// Override with full accounts data (includes schedules, scopes, contacts, revenues)
		accounts: accountsResult,
		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')
		},
		invoices: dashboard?.invoices ?? [],
		reports: dashboard?.reports ?? [],
		serviceScopes: dashboard?.serviceScopeTemplates ?? [],
		projectScopes: dashboard?.projectScopeTemplates ?? [],
		currentMonth: month
	};
};
