---
export const prerender = true;

export async function getStaticPaths() {
  try {
    const { getPosts, getTags } = await import("../../../../../lib/cms");
    const { filterPostsByTag, getTotalPages, getPostsPerPage } = await import("../../../../../lib/blog-utils");
    const [posts, tags] = await Promise.all([getPosts(), getTags()]);
    const fromTags = new Set((tags ?? []).map((t: { _slug?: string }) => t._slug ?? "").filter(Boolean));
    const fromPosts = new Set<string>();
    for (const p of posts ?? []) {
      for (const t of (p as { postTag?: unknown[] }).postTag ?? []) {
        const slug = typeof t === "string" ? t : (t as { _slug?: string })?._slug;
        if (slug) fromPosts.add(slug);
      }
    }
    const allSlugs = [...new Set([...fromTags, ...fromPosts])];
    const perPage = getPostsPerPage();
    const paths: { params: { tag: string; page: string } }[] = [];
    for (const tag of allSlugs) {
      const filtered = filterPostsByTag(posts ?? [], tag);
      const total = getTotalPages(filtered.length, perPage);
      for (let p = 2; p <= total; p++) paths.push({ params: { tag, page: String(p) } });
    }
    return paths;
  } catch {
    return [];
  }
}

const { tag, page } = Astro.params as { tag: string; page: string };
return Astro.redirect(`/posts/tag/${encodeURIComponent(tag)}/page/${encodeURIComponent(page)}`);
---
