import type { LayoutServerLoad } from './$types';
import { redirect, error } from '@sveltejs/kit';
import { client } from '$lib/graphql/client';
import { SERVICES_QUERY, type ServicesQueryResult } from '$lib/graphql/queries/services';
import { PROJECTS_QUERY, type ProjectsQueryResult } from '$lib/graphql/queries/projects';
import { getCurrentMonth, getMonthDateRange } from '$lib/utils/date';

export const load: LayoutServerLoad = async ({ url, parent, locals }) => {
	const parentData = await parent();
	const user = parentData.user;

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

	// Must be a TeamProfileType
	if (user.__typename !== 'TeamProfileType') {
		throw error(403, 'This area is only accessible to team members');
	}

	// Get month from URL params or default to current
	const month = url.searchParams.get('month') ?? getCurrentMonth();
	const { start, end } = getMonthDateRange(month);

	// Build filter - everyone on team interface sees only their assigned work
	const filter: Record<string, unknown> = {
		dateFrom: start,
		dateTo: end,
		teamProfileId: user.id
	};

	// Fetch services and projects
	const [servicesResult, projectsResult] = await Promise.all([
		client
			.query<ServicesQueryResult>({
				query: SERVICES_QUERY,
				variables: { filter, pagination: { limit: 100 } },
				context: { headers: { cookie: locals.cookie } },
				fetchPolicy: 'network-only'
			})
			.catch((err) => {
				console.error('Failed to fetch services:', err);
				return { data: null };
			}),
		client
			.query<ProjectsQueryResult>({
				query: PROJECTS_QUERY,
				variables: { filter, pagination: { limit: 100 } },
				context: { headers: { cookie: locals.cookie } },
				fetchPolicy: 'network-only'
			})
			.catch((err) => {
				console.error('Failed to fetch projects:', err);
				return { data: null };
			})
	]);

	const allServices = servicesResult.data?.services?.items ?? [];
	const allProjects = projectsResult.data?.projects?.items ?? [];

	return {
		...parentData,
		services: {
			scheduled: allServices.filter((s) => s.status === 'SCHEDULED'),
			inProgress: allServices.filter((s) => s.status === 'IN_PROGRESS'),
			completed: allServices.filter((s) => s.status === 'COMPLETED')
		},
		projects: {
			scheduled: allProjects.filter((p) => p.status === 'SCHEDULED'),
			inProgress: allProjects.filter((p) => p.status === 'IN_PROGRESS'),
			completed: allProjects.filter((p) => p.status === 'COMPLETED')
		},
		currentMonth: month
	};
};
