import { type CollectionEntry, getCollection } from "astro:content";

function publishedOnly(
  p: CollectionEntry<"blog">,
): p is CollectionEntry<"blog"> & { data: { pubDate: Date } } {
  return p.data.pubDate !== undefined;
}

export async function getPublishedPosts(
  tag?: string,
): Promise<CollectionEntry<"blog">[]> {
  const allPosts = (await getCollection("blog", publishedOnly)).sort(
    (a, b) => b.data.pubDate.valueOf() - a.data.pubDate.valueOf(),
  );
  return tag ? allPosts.filter((p) => p.data.tags?.includes(tag)) : allPosts;
}

export async function getAllTags(): Promise<string[]> {
  const posts = await getCollection("blog", publishedOnly);

  return Object.keys(
    Object.fromEntries(
      posts.flatMap((p) => p.data.tags || []).map((t) => [t, 1]),
    ),
  );
}
