import { error } from '@sveltejs/kit';
import type { components } from '$lib/generated/api';
import { createApiClient } from '$lib/shared/api.server';
import { getErrorMessage } from '$lib/shared/errors';

export async function load({ url, fetch, locals }) {
	const senderId = url.searchParams.get('senderId') || '';
	const receiverId = url.searchParams.get('receiverId') || '';
	const from = url.searchParams.get('from') || '';
	const to = url.searchParams.get('to') || '';
	const dir = url.searchParams.get('dir') || 'DESC';

	const canWrite =
		(locals.user as { groups?: { permissions: string[] }[] } | undefined)?.groups?.some((g) =>
			g.permissions.includes('WRITE_ALL')
		) ?? false;

	const api = createApiClient(fetch);

	let documents: components['schemas']['Document'][] = [];
	let senderName = '';
	let receiverName = '';

	const requests: Promise<void>[] = [];

	if (senderId) {
		requests.push(
			api
				.GET('/api/documents/conversation', {
					params: {
						query: {
							senderId,
							receiverId: receiverId || undefined,
							dir,
							from: from || undefined,
							to: to || undefined
						}
					}
				})
				.then((result) => {
					if (!result.response.ok) {
						const code = (result.error as unknown as { code?: string })?.code;
						throw error(result.response.status, getErrorMessage(code));
					}
					documents = result.data ?? [];
				})
		);

		requests.push(
			api.GET('/api/persons/{id}', { params: { path: { id: senderId } } }).then((result) => {
				if (!result.response.ok) {
					const code = (result.error as unknown as { code?: string })?.code;
					throw error(result.response.status, getErrorMessage(code));
				}
				const p = result.data as { displayName: string } | undefined;
				if (p) senderName = p.displayName;
			})
		);
	}

	if (receiverId) {
		requests.push(
			api.GET('/api/persons/{id}', { params: { path: { id: receiverId } } }).then((result) => {
				if (!result.response.ok) {
					const code = (result.error as unknown as { code?: string })?.code;
					throw error(result.response.status, getErrorMessage(code));
				}
				const p = result.data as { displayName: string } | undefined;
				if (p) receiverName = p.displayName;
			})
		);
	}

	await Promise.all(requests);

	return {
		documents,
		canWrite,
		initialValues: { senderName, receiverName },
		filters: { senderId, receiverId, from, to, dir }
	};
}
