import type { PageServerLoad } from './$types';
import { createServerClient } from '$lib/graphql/client';
import { redirect, error } from '@sveltejs/kit';
import { TEAM_PROFILE_QUERY, type TeamProfileQueryResult } from '$lib/graphql/queries/team';

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);

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

	if (!data?.teamProfile) {
		throw error(404, 'Team profile not found');
	}

	return {
		profile: data.teamProfile
	};
};
