import { fail, redirect } from '@sveltejs/kit';
import { env } from '$env/dynamic/private';
import { createApiClient } from '$lib/shared/api.server';
import { parseBackendError, getErrorMessage } from '$lib/shared/errors';
import { hasWriteAll } from '$lib/shared/server/permissions';

export async function load({
	fetch,
	locals,
	url
}: {
	fetch: typeof globalThis.fetch;
	locals: App.Locals;
	url: URL;
}) {
	if (!hasWriteAll(locals)) throw redirect(303, '/');

	const senderId = url.searchParams.get('senderId') || '';
	const receiverId = url.searchParams.get('receiverId') || '';

	const api = createApiClient(fetch);

	let initialSenderName = '';
	let initialReceivers: {
		id: string;
		firstName?: string;
		lastName: string;
		displayName: string;
	}[] = [];

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

	if (senderId) {
		requests.push(
			api.GET('/api/persons/{id}', { params: { path: { id: senderId } } }).then(({ data }) => {
				if (data) initialSenderName = data.displayName;
			})
		);
	}

	if (receiverId) {
		requests.push(
			api.GET('/api/persons/{id}', { params: { path: { id: receiverId } } }).then(({ data }) => {
				if (data)
					initialReceivers = [
						{
							id: data.id!,
							firstName: data.firstName,
							lastName: data.lastName,
							displayName: data.displayName
						}
					];
			})
		);
	}

	await Promise.all(requests);

	return {
		// Sender/receiver selection uses PersonTypeahead, which fetches its own results on
		// demand — the page never consumes a pre-loaded full person list, so none is fetched.
		persons: [] as never[],
		initialSenderId: senderId,
		initialSenderName,
		initialReceivers
	};
}

async function submitNewDocument(
	request: Request,
	fetch: typeof globalThis.fetch,
	metadataComplete: boolean
) {
	const baseUrl = env.API_INTERNAL_URL || 'http://localhost:8080';
	const formData = await request.formData();
	formData.set('metadataComplete', String(metadataComplete));

	const res = await fetch(`${baseUrl}/api/documents`, {
		method: 'POST',
		body: formData
	});

	if (!res.ok) {
		const backendError = await parseBackendError(res);
		return fail(res.status, { error: getErrorMessage(backendError?.code) });
	}

	const created = await res.json();
	throw redirect(303, `/documents/${created.id}`);
}

export const actions = {
	save: async ({ request, fetch }: { request: Request; fetch: typeof globalThis.fetch }) => {
		return submitNewDocument(request, fetch, false);
	},

	saveReviewed: async ({
		request,
		fetch
	}: {
		request: Request;
		fetch: typeof globalThis.fetch;
	}) => {
		return submitNewDocument(request, fetch, true);
	}
};
