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;

	// the following feed needs a viewer to resolve the followed set; bobbin 400s without one
	const followingOnly = event.url.searchParams.get("following") === "true" && viewer !== undefined;

	try {
		// output key is `feed`, not `items`, so the pagination.ts helpers don't apply
		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");
	}
};
