---
export const prerender = true;

export async function getStaticPaths() {
  try {
    const { getPosts, getTags } = await import("../../../lib/cms");
    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])];
    return allSlugs.map((tag) => ({ params: { tag } }));
  } catch {
    return [];
  }
}

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