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

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

	const projectResult = await new GetProjectStore().fetch({
		event,
		metadata: { cookie: locals.cookie },
		variables: { id: params.project }
	});

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

	// Fetch the project scope if it exists
	let scopeResult = null;
	const scopeId = projectResult.data.project.scopeId;
	if (scopeId) {
		const scopeGlobalId = toGlobalId('ProjectScopeType', scopeId);
		scopeResult = await new ProjectScopeStore().fetch({
			event,
			metadata: { cookie: locals.cookie },
			variables: { id: scopeGlobalId }
		});
	}

	return {
		...parentData,
		project: projectResult,
		scope: scopeResult
	};
};
