import { error } from '@sveltejs/kit';
import type { PageServerLoad } from './$types';
import {
	GetServiceStore,
	ServiceSessionByServiceStore,
	ScopeByAddressStore,
	ServiceSessionPhotosStore,
	ServiceSessionVideosStore
} from '$houdini';
import { fromGlobalId } from '$lib/utils/relay';

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

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

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

	const foundService = allServices.find((s) => s.id === serviceId);

	// If not found in parent data, fetch directly
	let service;
	if (foundService) {
		service = foundService;
	} else {
		const serviceStore = new GetServiceStore();
		const serviceData = await serviceStore.fetch({ ...fetchParams, variables: { id: serviceId } });
		service = serviceData.data?.service;

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

	// Get the service UUID from the global ID for querying
	const serviceUuid = fromGlobalId(serviceId);

	// Fetch session data if service is in progress or completed
	let session = null;
	if (service.status === 'IN_PROGRESS' || service.status === 'COMPLETED') {
		const sessionStore = new ServiceSessionByServiceStore();
		const sessionData = await sessionStore.fetch({
			...fetchParams,
			variables: { serviceId: serviceUuid }
		});
		session = sessionData?.data?.serviceSessions?.[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 ServiceSessionPhotosStore()
					.fetch({ ...fetchParams, variables: { sessionId: sessionUuid } })
					.catch((err) => {
						console.error('Failed to fetch session photos:', err);
						return { data: { serviceSessionImages: [] } };
					}),
				new ServiceSessionVideosStore()
					.fetch({ ...fetchParams, variables: { sessionId: sessionUuid } })
					.catch((err) => {
						console.error('Failed to fetch session videos:', err);
						return { data: { serviceSessionVideos: [] } };
					})
			]);

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

	// Fetch scope data if service has an accountAddressId
	let scopeData = null;
	if (service.accountAddressId) {
		const scopeStore = new ScopeByAddressStore();
		scopeData = await scopeStore.fetch({
			...fetchParams,
			variables: { accountAddressId: service.accountAddressId }
		});
	}

	return {
		service,
		serviceUuid,
		session,
		scope: scopeData?.data?.scopes?.[0] ?? null
	};
};
