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 { error, redirect } from '@sveltejs/kit';

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 [projectResult, teamResult, sessionResult] = 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 };
			})
	]);

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

	// Verify the user is assigned to this project (for TEAM_MEMBER role)
	const project = projectResult.data.project;
	if (user.role === 'TEAM_MEMBER') {
		const isAssigned = project.teamMembers.some((m) => m.teamProfileId === user.id);
		if (!isAssigned) {
			throw error(403, 'You are not assigned to this project');
		}
	}

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