import { notFound } from 'next/navigation';
import type { Metadata } from "next";
import { getCachedPosts, getCachedAllPosts } from "@/services/wp";
import Pagination from "@/components/Pagination/Pagination";
import Listing from "@/components/Listing/Listing";


const PaginatedInsights = async (props: { params: Promise<{ page: string }> }) => {
  const params = await props.params;
  const currentPage = parseInt(params.page) || 2;
  const perPage = parseInt(process.env.BLOG_PAGINATION_PER_PAGE!) || 6;

  const posts = await getCachedPosts(currentPage, perPage);

  if (posts.posts.length === 0) {
    notFound();
  }

  const totalPages = Math.ceil(posts._paging.total / perPage);

  return (
    <>
      <Listing posts={posts.posts}>
        <div className="mt-sm col-span-full flex items-center justify-center">
          <Pagination totalPages={totalPages} currentPage={currentPage} />
        </div>
      </Listing>
    </>
  );
};

export const generateMetadata = async (props: { params: Promise<{ page: string }> }): Promise<Metadata> => {
  const params = await props.params;
  const { page } = params;

  const baseUrl = process.env.SITE_URL || "https://teapot.agency";
  const canonicalUrl = `${baseUrl}insights`;

  return {
    title: `Insights - page ${page} | Teapot Creative`,
    alternates: {
      canonical: canonicalUrl,
    },
  };
}

export const generateStaticParams = async () => {
  const posts = await getCachedAllPosts(100);
  const totalPages = Math.ceil(posts.length / 6);

  let paginationItems: { page: string }[] = [];

  for (let index = 1; index <= totalPages; index++) {
    if (index < 2) continue;

    paginationItems.push({
      page: `${index}`,
    });
  }

  return paginationItems;
};


export default PaginatedInsights;
