import type { PageServerLoad } from './$types';
import { createServerClient } from '$lib/graphql/client';
import { PROJECT_QUERY, type ProjectQueryResult } from '$lib/graphql/queries/projects';
import { TEAM_PROFILES_QUERY, type TeamProfilesQueryResult } from '$lib/graphql/queries/team';
import {
	LATEST_PROJECT_SESSION_QUERY,
	type LatestProjectSessionQueryResult
} from '$lib/graphql/queries/session';
import { WAVE_PRODUCTS, type WaveProduct } from '$lib/graphql/queries/wave';
import { error, redirect } 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);

	const [projectResult, teamResult, sessionResult, waveProductsResult] = await Promise.all([
		client
			.query<ProjectQueryResult>({
				query: PROJECT_QUERY,
				variables: { id: params.project }
			})
			.catch((err) => {
				console.error('Failed to fetch project:', err);
				return { data: null };
			}),
		client
			.query<TeamProfilesQueryResult>({
				query: TEAM_PROFILES_QUERY
			})
			.catch((err) => {
				console.error('Failed to fetch team profiles:', err);
				return { data: null };
			}),
		client
			.query<LatestProjectSessionQueryResult>({
				query: LATEST_PROJECT_SESSION_QUERY,
				variables: { projectId: params.project }
			})
			.catch((err) => {
				console.error('Failed to fetch session:', err);
				return { data: null };
			}),
		client
			.query<{ waveProducts: WaveProduct[] }>({
				query: WAVE_PRODUCTS
			})
			.catch((err) => {
				console.error('Failed to fetch wave products:', err);
				return { data: null };
			})
	]);

	if (!projectResult.data?.project) {
		throw error(404, 'Project not found');
	}

	return {
		project: projectResult.data.project,
		teamProfiles: teamResult.data?.teamProfiles ?? [],
		session: sessionResult.data?.latestProjectSession ?? null,
		waveProducts: waveProductsResult.data?.waveProducts ?? []
	};
};
