---
import { getEmDashCollection, getTermsForEntries } from "emdash";
import { Image } from "emdash/ui";
import Base from "../../layouts/Base.astro";

const { entries: posts, cacheHint } = await getEmDashCollection("posts", {
	orderBy: { published_at: "desc" },
});
Astro.cache.set(cacheHint);

// Single batched query for tags across every post, instead of calling
// getEntryTerms() per post (which would be N round-trips).
const tagsByEntry = await getTermsForEntries(
	"posts",
	posts.map((p) => p.data.id),
	"tag",
);
const postsWithTags = posts.map((post) => ({
	post,
	tags: tagsByEntry.get(post.data.id) ?? [],
}));
---

<Base title="All Posts">
	<h1>Posts</h1>

	{
		postsWithTags.length === 0 ? (
			<p>No posts yet.</p>
		) : (
			<ul>
				{postsWithTags.map(({ post, tags }) => (
					<li>
						<a href={`/posts/${post.id}`}>
							{post.data.featured_image && (
								<Image image={post.data.featured_image} />
							)}
							<h2>{post.data.title}</h2>
						</a>
						{post.data.excerpt && <p>{post.data.excerpt}</p>}
						{tags.length > 0 && (
							<div>
								{tags.map((t) => (
									<a href={`/tag/${t.slug}`}>{t.label}</a>
								))}
							</div>
						)}
					</li>
				))}
			</ul>
		)
	}
</Base>
