import { createBobbinClient } from "$lib/api/client";
import { jsonGet } from "$lib/api/_request";
import { toHttpError } from "$lib/api/load";
import type * as ShTangledFeedGetTimeline from "$lib/api/lexicons/types/sh/tangled/feed/getTimeline";
import type { PageLoad } from "./$types";

const PAGE_LIMIT = 50;

export const load: PageLoad = async (event) => {
	const parent = await event.parent();
	const ctx = createBobbinClient({ serviceUrl: parent.publicConfig.bobbinUrl, fetch: event.fetch });
	const viewer = parent.auth?.did;

	const followingOnly = event.url.searchParams.get("following") === "true" && viewer !== undefined;

	try {
		const { feed } = await jsonGet<ShTangledFeedGetTimeline.$output>(
			ctx,
			"sh.tangled.feed.getTimeline",
			{ viewer, followingOnly, limit: PAGE_LIMIT }
		);
		return { feed, followingOnly, signedIn: viewer !== undefined };
	} catch (cause) {
		toHttpError(cause, "Could not load timeline");
	}
};
