import { error, redirect } from '@sveltejs/kit';
import { createApiClient, extractErrorCode } from '$lib/shared/api.server';
import { getErrorMessage } from '$lib/shared/errors';
import { inferredRelationshipLabel } from '$lib/person/relationshipLabels';

export async function load({ params, fetch }) {
	const { id } = params;
	const api = createApiClient(fetch);

	const [docResult, geschichtenResult] = await Promise.all([
		api.GET('/api/documents/{id}', { params: { path: { id } } }),
		api.GET('/api/geschichten', {
			params: { query: { status: 'PUBLISHED', documentId: id } }
		})
	]);

	if (docResult.response.status === 401) throw redirect(302, '/login');

	if (!docResult.response.ok) {
		throw error(docResult.response.status, getErrorMessage(extractErrorCode(docResult.error)));
	}

	const document = docResult.data!;
	const inferredRelationship = await loadInferredRelationship(api, document);
	const geschichten = geschichtenResult.data ?? [];

	return { document, inferredRelationship, geschichten };
}

async function loadInferredRelationship(
	api: ReturnType<typeof createApiClient>,
	document: {
		sender?: { id: string; familyMember?: boolean } | null;
		receivers?: { id: string; familyMember?: boolean }[];
	}
): Promise<{ labelFromA: string; labelFromB: string } | null> {
	const sender = document.sender;
	const receivers = document.receivers ?? [];

	// The badge is shown only when both endpoints are family members and the
	// document has exactly one receiver.
	if (!sender?.familyMember) return null;
	if (receivers.length !== 1) return null;
	const receiver = receivers[0];
	if (!receiver?.familyMember) return null;

	const result = await api.GET('/api/persons/{aId}/relationship-to/{bId}', {
		params: { path: { aId: sender.id, bId: receiver.id } }
	});

	if (result.response.status === 404) return null;
	if (!result.response.ok || !result.data) return null;

	return {
		labelFromA: inferredRelationshipLabel(result.data.labelFromA),
		labelFromB: inferredRelationshipLabel(result.data.labelFromB)
	};
}
