---
import ArticlesView from "../../../../../components/ArticlesView.astro";
import NotFoundPage from "../../../../../components/NotFoundPage.astro";
import { getPublishedArticles, getCategoryNames, getCategories, slugToCategory, pageSlice, lastPageOf } from "../../../../../lib/articles";

export const prerender = false;

const all = await getPublishedArticles();
const categoryNames = await getCategoryNames();
const categories = getCategories(all, categoryNames);
const routeSlug = String(Astro.params.slug || "");
const categoryName = slugToCategory(routeSlug, categoryNames);
const filtered = categoryName ? all.filter((item) => item.data.category === categoryName) : [];
const pageValue = String(Astro.params.page || "");
const page = /^\d+$/.test(pageValue) ? Number(pageValue) : 0;
const lastPage = lastPageOf(filtered.length);
const valid = Boolean(categoryName) && Number.isSafeInteger(page) && page >= 2 && page <= lastPage;
if (!valid) Astro.response.status = 404;
else Astro.response.headers.set("Cache-Control", "public, max-age=0, must-revalidate");
---
{valid
  ? <ArticlesView items={pageSlice(filtered, page)} {categories} totalCount={all.length} activeSlug={routeSlug} activeName={categoryName!} currentPage={page} {lastPage} basePath={`/articles/topic/${routeSlug}`} />
  : <NotFoundPage />}
