import { gitTarget, tags } from "$lib/api/gitclient";
import { REF_LIMIT } from "$lib/api/repoIndex";
import { toTagSummary } 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 tags(git, REF_LIMIT, cursor);
	const list = (results.tags ?? []).map(toTagSummary);
	const total = results.total ?? 0;
	const pageCount =
		total > 0 ? Math.ceil(total / REF_LIMIT) : page + (list.length === REF_LIMIT ? 1 : 0);
	return {
		tags: list,
		page,
		pageCount
	};
};
