import type { PageServerLoad } from './$types';
import { createServerClient } from '$lib/graphql/client';
import { REPORTS_QUERY, type ReportsQueryResult } from '$lib/graphql/queries/reports';
import { TEAM_PROFILES_QUERY, type TeamProfilesQueryResult } from '$lib/graphql/queries/team';
import { redirect } from '@sveltejs/kit';

const DEFAULT_LIMIT = 20;

export const load: PageServerLoad = async ({ locals, parent, url }) => {
	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, '/');
	}

	// Parse URL parameters
	const teamProfileId = url.searchParams.get('teamProfileId') || null;
	const status = url.searchParams.get('status') || null;
	const page = parseInt(url.searchParams.get('page') || '1', 10);
	const limit = parseInt(url.searchParams.get('limit') || String(DEFAULT_LIMIT), 10);
	const offset = (page - 1) * limit;

	if (!locals.cookie) {
		return {
			reports: { items: [], totalCount: 0, hasNextPage: false },
			teamProfiles: [],
			teamProfileId,
			status,
			page,
			limit
		};
	}

	const client = createServerClient(locals.cookie);

	// Fetch reports and team profiles in parallel
	const [reportsResult, profilesResult] = await Promise.all([
		client
			.query<ReportsQueryResult>({
				query: REPORTS_QUERY,
				variables: {
					filter: {
						teamProfileId: teamProfileId || undefined,
						status: status || undefined
					},
					pagination: {
						offset,
						limit
					}
				}
			})
			.catch((err) => {
				console.error('Failed to fetch reports:', err);
				return { data: null };
			}),
		client
			.query<TeamProfilesQueryResult>({
				query: TEAM_PROFILES_QUERY
			})
			.catch((err) => {
				console.error('Failed to fetch team profiles:', err);
				return { data: null };
			})
	]);

	return {
		reports: reportsResult.data?.reports ?? { items: [], totalCount: 0, hasNextPage: false },
		teamProfiles: profilesResult.data?.teamProfiles ?? [],
		teamProfileId,
		status,
		page,
		limit
	};
};
