---
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 valid = Boolean(categoryName);
const filtered = valid ? all.filter((item) => item.data.category === categoryName) : [];
if (!valid) Astro.response.status = 404;
else Astro.response.headers.set("Cache-Control", "public, max-age=0, must-revalidate");
---
{valid
  ? <ArticlesView items={pageSlice(filtered, 1)} {categories} totalCount={all.length} activeSlug={routeSlug} activeName={categoryName!} currentPage={1} lastPage={lastPageOf(filtered.length)} basePath={`/articles/topic/${routeSlug}`} />
  : <NotFoundPage />}
