import type { PageServerLoad } from './$types';
import { error } from '@sveltejs/kit';
import {
	GetProjectStore,
	ProjectSessionByProjectStore,
	ProjectScopeStore,
	TeamProfilesStore,
	ProjectSessionPhotosStore,
	ProjectSessionVideosStore
} from '$houdini';
import { fromGlobalId, toGlobalId } from '$lib/utils/relay';

export const load: PageServerLoad = async (event) => {
	const { params, locals, parent } = event;
	const parentData = await parent();
	const fetchParams = { event, metadata: { cookie: locals.cookie } };

	const projectResult = await new GetProjectStore().fetch({
		...fetchParams,
		variables: { id: params.project }
	});

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

	const project = projectResult.data.project;
	const projectUuid = fromGlobalId(params.project);

	// Fetch session data for completed projects
	let sessionResult = null;
	let sessionPhotos: Awaited<ReturnType<ProjectSessionPhotosStore['fetch']>>['data'] | null = null;
	let sessionVideos: Awaited<ReturnType<ProjectSessionVideosStore['fetch']>>['data'] | null = null;

	if (project.status === 'COMPLETED') {
		sessionResult = await new ProjectSessionByProjectStore().fetch({
			...fetchParams,
			variables: { projectId: projectUuid }
		});

		// Fetch photos and videos separately to handle missing file errors gracefully
		const session = sessionResult?.data?.projectSessions?.[0];
		if (session) {
			const sessionUuid = fromGlobalId(session.id);
			const [photosResult, videosResult] = await Promise.all([
				new ProjectSessionPhotosStore()
					.fetch({ ...fetchParams, variables: { sessionId: sessionUuid } })
					.catch((err) => {
						console.error('Failed to fetch session photos:', err);
						return null;
					}),
				new ProjectSessionVideosStore()
					.fetch({ ...fetchParams, variables: { sessionId: sessionUuid } })
					.catch((err) => {
						console.error('Failed to fetch session videos:', err);
						return null;
					})
			]);

			sessionPhotos = photosResult?.data ?? null;
			sessionVideos = videosResult?.data ?? null;
		}
	}

	// Fetch the project scope for task name lookups
	let scopeResult = null;
	if (project.scopeId) {
		const scopeGlobalId = toGlobalId('ProjectScopeType', project.scopeId);
		scopeResult = await new ProjectScopeStore().fetch({
			...fetchParams,
			variables: { id: scopeGlobalId }
		});
	}

	// Fetch team profiles for attribution
	const teamProfilesResult = await new TeamProfilesStore().fetch(fetchParams);

	return {
		...parentData,
		project: projectResult,
		session: sessionResult,
		sessionPhotos,
		sessionVideos,
		scope: scopeResult,
		teamProfiles: teamProfilesResult
	};
};
