import { branches, gitTarget } from "$lib/api/gitclient";
import { REF_LIMIT } from "$lib/api/repoIndex";
import { toBranchSummary } from "$lib/api/repo";
import type { PageLoad } from "./$types";

export const load: PageLoad = async (event) => {
	const parent = await event.parent();
	const git = gitTarget(parent.publicConfig, parent.repo, event.fetch);
	const rawPage = event.url.searchParams.get("page") ?? "";
	const parsed = /^\d+$/.test(rawPage) ? Number(rawPage) : 1;
	const page = parsed >= 1 ? parsed : 1;
	const cursor = page > 1 ? String((page - 1) * REF_LIMIT) : undefined;
	const results = await branches(git, REF_LIMIT, cursor);
	const list = (results.branches ?? []).map(toBranchSummary);
	const total = results.total ?? 0;
	const pageCount =
		total > 0 ? Math.ceil(total / REF_LIMIT) : page + (list.length === REF_LIMIT ? 1 : 0);
	return {
		branches: list,
		page,
		pageCount
	};
};
