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

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

	// Redirect if not authenticated or not a team member
	if (!user || user.__typename !== 'TeamProfileType') {
		throw redirect(303, '/');
	}

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

	const client = createServerClient(locals.cookie);

	const { data } = await client
		.query<ReportQueryResult>({
			query: REPORT_QUERY,
			variables: { id: params.report }
		})
		.catch((err) => {
			console.error('Failed to fetch report:', err);
			throw error(500, 'Failed to load report');
		});

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

	// Verify the report belongs to this team member (unless admin/team leader)
	if (user.role === 'TEAM_MEMBER' && data.report.teamProfileId !== user.id) {
		throw error(403, 'You do not have access to this report');
	}

	return {
		report: data.report
	};
};
