import type { PageServerLoad } from './$types';
import { createServerClient } from '$lib/graphql/client';
import {
	REPORT_QUERY,
	ELIGIBLE_SERVICES_QUERY,
	ELIGIBLE_PROJECTS_QUERY,
	type ReportQueryResult,
	type EligibleServicesQueryResult,
	type EligibleProjectsQueryResult
} from '$lib/graphql/queries/reports';
import { redirect, error } from '@sveltejs/kit';

export const load: PageServerLoad = async ({ locals, parent, params }) => {
	const { user } = await parent();

	// Redirect if not authenticated or not an admin/team leader
	if (
		!user ||
		user.__typename !== 'TeamProfileType' ||
		(user.role !== 'ADMIN' && user.role !== 'TEAM_LEADER')
	) {
		throw redirect(303, '/');
	}

	if (!locals.cookie) {
		throw error(401, 'Not authenticated');
	}

	const client = createServerClient(locals.cookie);

	// Fetch the report
	const reportResult = await client
		.query<ReportQueryResult>({
			query: REPORT_QUERY,
			variables: { id: params.report }
		})
		.catch((err) => {
			console.error('Failed to fetch report:', err);
			return { data: null };
		});

	const report = reportResult.data?.report;

	if (!report) {
		throw error(404, 'Report not found');
	}

	// Fetch eligible services and projects
	const [eligibleServicesResult, eligibleProjectsResult] = await Promise.all([
		client
			.query<EligibleServicesQueryResult>({
				query: ELIGIBLE_SERVICES_QUERY,
				variables: {
					teamProfileId: report.teamProfileId,
					dateFrom: report.startDate,
					dateTo: report.endDate
				}
			})
			.catch((err) => {
				console.error('Failed to fetch eligible services:', err);
				return { data: null };
			}),
		client
			.query<EligibleProjectsQueryResult>({
				query: ELIGIBLE_PROJECTS_QUERY,
				variables: {
					teamProfileId: report.teamProfileId,
					dateFrom: report.startDate,
					dateTo: report.endDate
				}
			})
			.catch((err) => {
				console.error('Failed to fetch eligible projects:', err);
				return { data: null };
			})
	]);

	return {
		report,
		eligibleServices: eligibleServicesResult.data?.eligibleServicesForReport ?? [],
		eligibleProjects: eligibleProjectsResult.data?.eligibleProjectsForReport ?? []
	};
};
