import type { PageServerLoad } from './$types';
import { error } from '@sveltejs/kit';
import { GetServiceStore, ScopeByAddressStore } from '$houdini';

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

	const serviceResult = await new GetServiceStore().fetch({
		event,
		metadata: { cookie: locals.cookie },
		variables: { id: params.service }
	});

	if (!serviceResult.data?.service) {
		throw error(404, 'Service not found');
	}

	// Fetch the active scope for this service's address
	let scopeResult = null;
	const accountAddressId = serviceResult.data.service.accountAddressId;
	if (accountAddressId) {
		scopeResult = await new ScopeByAddressStore().fetch({
			event,
			metadata: { cookie: locals.cookie },
			variables: { accountAddressId }
		});
	}

	return {
		...parentData,
		service: serviceResult,
		scope: scopeResult
	};
};
