import type { PageServerLoad } from './$types';
import { error } from '@sveltejs/kit';
import {
	GetServiceStore,
	ServiceSessionByServiceStore,
	ScopeByAddressStore,
	TeamProfilesStore,
	ServiceSessionPhotosStore,
	ServiceSessionVideosStore
} from '$houdini';
import { fromGlobalId } 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 serviceResult = await new GetServiceStore().fetch({
		...fetchParams,
		variables: { id: params.service }
	});

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

	const service = serviceResult.data.service;
	const serviceUuid = fromGlobalId(params.service);

	// Fetch session data for completed services
	let sessionResult = null;
	let sessionPhotos: Awaited<ReturnType<ServiceSessionPhotosStore['fetch']>>['data'] | null = null;
	let sessionVideos: Awaited<ReturnType<ServiceSessionVideosStore['fetch']>>['data'] | null = null;

	if (service.status === 'COMPLETED') {
		sessionResult = await new ServiceSessionByServiceStore().fetch({
			...fetchParams,
			variables: { serviceId: serviceUuid }
		});

		// Fetch photos and videos separately to handle missing file errors gracefully
		const session = sessionResult?.data?.serviceSessions?.[0];
		if (session) {
			const sessionUuid = fromGlobalId(session.id);
			const [photosResult, videosResult] = await Promise.all([
				new ServiceSessionPhotosStore()
					.fetch({ ...fetchParams, variables: { sessionId: sessionUuid } })
					.catch((err) => {
						console.error('Failed to fetch session photos:', err);
						return null;
					}),
				new ServiceSessionVideosStore()
					.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 active scope for task name lookups
	let scopeResult = null;
	if (service.accountAddressId) {
		scopeResult = await new ScopeByAddressStore().fetch({
			...fetchParams,
			variables: { accountAddressId: service.accountAddressId }
		});
	}

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

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