import type { PageServerLoad } from './$types';
import { createServerClient } from '$lib/graphql/client';
import { REPORTS_QUERY, type ReportsQueryResult } from '$lib/graphql/queries/reports';
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 a team member
	if (!user || user.__typename !== 'TeamProfileType') {
		throw redirect(303, '/');
	}

	// Parse URL parameters
	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 },
			status,
			page,
			limit
		};
	}

	const client = createServerClient(locals.cookie);

	// Team members see their own reports only
	const reportsResult = await client
		.query<ReportsQueryResult>({
			query: REPORTS_QUERY,
			variables: {
				filter: {
					teamProfileId: user.id,
					status: status || undefined
				},
				pagination: {
					offset,
					limit
				}
			}
		})
		.catch((err) => {
			console.error('Failed to fetch reports:', err);
			return { data: null };
		});

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