import { notFound } from "next/navigation";
import { listPublishedPosts } from "@/lib/services/posts";
import { EmptyState } from "./EmptyState";
import { PaginationNav } from "./PaginationNav";
import { PostCard } from "./PostCard";

/**
 * Shared published-post listing used by /, /posts and /tags/[slug].
 * Requests beyond the last page 404 instead of rendering an empty page.
 */
export async function PostListSection({
  page,
  perPage,
  excerptWords,
  tagId,
  basePath,
  emptyMessage,
}: {
  page: number;
  perPage: number;
  excerptWords: number;
  tagId?: number;
  basePath: string;
  emptyMessage: string;
}) {
  const result = await listPublishedPosts({ page, perPage, tagId });

  if (page > 1 && page > result.pageCount) notFound();
  if (result.total === 0) return <EmptyState>{emptyMessage}</EmptyState>;

  return (
    <>
      <div className="grid gap-6">
        {result.items.map((post) => (
          <PostCard key={post.id} post={post} excerptWords={excerptWords} />
        ))}
      </div>
      <PaginationNav page={result.page} pageCount={result.pageCount} basePath={basePath} />
    </>
  );
}
