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

export const load: PageServerLoad = async (event) => {
	const { params, parent, locals } = event;
	const data = await parent();
	const projectId = params.project;

	// Fetch params for Houdini stores
	const fetchParams = { event, metadata: { cookie: locals.cookie } };

	// Search through all status categories to find the project in parent data
	const allProjects = [
		...(data.projects.scheduled ?? []),
		...(data.projects.inProgress ?? []),
		...(data.projects.completed ?? [])
	];

	const foundProject = allProjects.find((p) => p.id === projectId);

	// If not found in parent data, fetch directly
	let project;
	if (foundProject) {
		project = foundProject;
	} else {
		const projectStore = new GetProjectStore();
		const projectData = await projectStore.fetch({ ...fetchParams, variables: { id: projectId } });
		project = projectData.data?.project;

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

	// Get the project UUID from the global ID for querying
	const projectUuid = fromGlobalId(projectId);

	// Fetch session data if project is in progress or completed
	let session = null;
	if (project.status === 'IN_PROGRESS' || project.status === 'COMPLETED') {
		const sessionStore = new ProjectSessionByProjectStore();
		const sessionData = await sessionStore.fetch({
			...fetchParams,
			variables: { projectId: projectUuid }
		});
		session = sessionData?.data?.projectSessions?.[0] ?? null;

		// Fetch photos and videos separately to handle missing file errors gracefully
		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 { data: { projectSessionImages: [] } };
					}),
				new ProjectSessionVideosStore()
					.fetch({ ...fetchParams, variables: { sessionId: sessionUuid } })
					.catch((err) => {
						console.error('Failed to fetch session videos:', err);
						return { data: { projectSessionVideos: [] } };
					})
			]);

			// Merge photos and videos into session object
			session = {
				...session,
				photos: photosResult?.data?.projectSessionImages ?? [],
				videos: videosResult?.data?.projectSessionVideos ?? []
			};
		}
	}

	// Fetch scope data if project has a scopeId
	// Note: project.scopeId is a UUID, but projectScope query expects a Relay Global ID
	let scopeData = null;
	if (project.scopeId) {
		const scopeStore = new ProjectScopeStore();
		const scopeGlobalId = toGlobalId('ProjectScopeType', project.scopeId);
		scopeData = await scopeStore.fetch({ ...fetchParams, variables: { id: scopeGlobalId } });
	}

	return {
		project,
		projectId,
		projectUuid,
		session,
		scope: scopeData?.data?.projectScope ?? null
	};
};
