import type { PageServerLoad } from './$types';
import { createServerClient } from '$lib/graphql/client';
import { SERVICE_QUERY, type ServiceQueryResult } from '$lib/graphql/queries/services';
import { error } from '@sveltejs/kit';

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

	// Must be a customer profile
	if (!user || user.__typename !== 'CustomerProfileType') {
		throw error(403, 'Access denied');
	}

	if (!locals.cookie) {
		throw error(401, 'Not authenticated');
	}

	const client = createServerClient(locals.cookie);

	const serviceResult = await client
		.query<ServiceQueryResult>({
			query: SERVICE_QUERY,
			variables: { id: params.service }
		})
		.catch((err) => {
			console.error('Failed to fetch service:', err);
			return { data: null };
		});

	const service = serviceResult.data?.service;

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

	// Verify customer has access to this service
	const customerIds = customers?.map((c: { id: string }) => c.id) ?? [];
	const serviceCustomerId = service.account?.customer?.id;

	if (!serviceCustomerId || !customerIds.includes(serviceCustomerId)) {
		throw error(403, 'You do not have access to this service');
	}

	return {
		service
	};
};
