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

type SessionPhoto = ServiceSessionPhotos$result['serviceSessionImages'][number];
type SessionVideo = ServiceSessionVideos$result['serviceSessionVideos'][number];

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

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

	// Fetch the service first (needed to check status and get accountAddressId)
	const serviceData = await new GetServiceStore().fetch({
		...fetchParams,
		variables: { id: serviceId }
	});

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

	// Build parallel fetch promises based on service state
	const needsSession = service.status === 'IN_PROGRESS' || service.status === 'COMPLETED';

	// Fetch session and scope in parallel
	const [sessionResult, scopeResult] = await Promise.all([
		// Session fetch (only if needed)
		needsSession
			? new ServiceSessionByServiceStore()
					.fetch({ ...fetchParams, variables: { serviceId: serviceUuid } })
					.catch(() => ({ data: { serviceSessions: [] } }))
			: Promise.resolve(null),
		// Scope fetch (only if has address)
		service.accountAddressId
			? new ScopeByAddressStore()
					.fetch({ ...fetchParams, variables: { accountAddressId: service.accountAddressId } })
					.catch(() => ({ data: { scopes: [] } }))
			: Promise.resolve(null)
	]);

	const baseSession = sessionResult?.data?.serviceSessions?.[0] ?? null;
	let photos: SessionPhoto[] = [];
	let videos: SessionVideo[] = [];

	// If we have a session, fetch photos and videos in parallel
	if (baseSession) {
		const sessionUuid = fromGlobalId(baseSession.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: [] as SessionPhoto[] } };
				}),
			new ServiceSessionVideosStore()
				.fetch({ ...fetchParams, variables: { sessionId: sessionUuid } })
				.catch((err) => {
					console.error('Failed to fetch session videos:', err);
					return { data: { serviceSessionVideos: [] as SessionVideo[] } };
				})
		]);

		photos = photosResult?.data?.serviceSessionImages ?? [];
		videos = videosResult?.data?.serviceSessionVideos ?? [];
	}

	// Combine session with photos/videos
	const session = baseSession ? { ...baseSession, photos, videos } : null;

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