import { error } from "@sveltejs/kit";
import { browser } from "$app/environment";
import { hasTextView, loadRepoBlob } from "$lib/api/blob";
import { pierreFileOptions } from "$lib/components/repo/pierre";
import { baseName } from "$lib/components/repo/urls";
import type { PageLoad } from "./$types";

// the ref is a single encoded segment, `feature/x` arrives intact. the
// rest param is already the path as git knows it
export const load: PageLoad = async (event) => {
	// no path means the knot would 400 on the empty path, 404 instead
	if (event.params.path === "") error(404, "Not found");
	const parent = await event.parent();
	const blob = await loadRepoBlob(event, parent, event.params.ref, event.params.path);

	// same deal as the commit page: prerender the code view's shadow dom on
	// the server, pierre paints client navigations itself
	let prerenderedHTML: string | undefined;
	if (
		!browser &&
		blob.contents !== null &&
		!blob.fileTooLarge &&
		hasTextView(blob.kind) &&
		blob.defaultView === "code"
	) {
		const { preloadFile } = await import("@pierre/diffs/ssr");
		const prerendered = await preloadFile({
			file: { name: baseName(blob.path), contents: blob.contents },
			options: pierreFileOptions(false)
		});
		prerenderedHTML = prerendered.prerenderedHTML;
	}

	return { ...blob, prerenderedHTML };
};
