import BlogContent from "@/sections/BlogContent";
import getPostMetadata from "@/utils/getPostMetaData";
import { headers } from "next/headers";
import React from "react";
import Spacer from "@/components/Utilities/Spacer";
import pb from "@/lib/pocketbase";
import Footer from "@/components/Footer";
import Background from "@/components/Utilities/Background";

export async function generateMetadata({
  params,
}: {
  params: { slug: string };
}) {
  const { slug } = params;
  const headersList = headers();
  const siteURL = headersList.get("host");
  pb.autoCancellation(false);
  const post = await pb.collection("blog").getFirstListItem(`slug="${slug}"`, {
    requestKey: "metaData",
  });
  pb.autoCancellation(true);

  return {
    title: `${post.title}`,
    description: `${post.subtitle}`,
    alternates: {
      canonical: `https://${siteURL}/blogs/${slug}`,
    },
  };
}

export const generateStaticParams = async () => {
  const posts = await getPostMetadata();
  return posts.map((post) => ({
    slug: post.slug,
    id: post.id,
  }));
};

const PostPage = async (props: any) => {
  const post = await pb
    .collection("blog")
    .getFirstListItem(`slug="${props.params.slug}"`, {
      requestKey: "post",
    });
  return (
    <main
      id="content"
      role="main"
      className="h-full flex-grow flex flex-col bg-base-100 max-w-screen"
    >
      <Background>
        <div className="flex flex-col h-full w-full md:max-w-3xl md:mx-auto max-w-screen mb-8">
          <Spacer className="pt-32" />
          <BlogContent post={post} />
        </div>
        <Footer />
      </Background>
    </main>
  );
};

export default PostPage;
