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 }) {
  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} | FastPocket`,
    authors: [
      {
        name: post.author || "Samuel Wyndham"
      }
    ],
    description: post.description,
    keywords: post.keywords,
    openGraph: {
      title: `${post.title} | FastPocket`,
      description: post.description,
      type: "article",
      url: `https://${siteURL}/blogs/${post.slug}`,
      publishedTime: post.created,
      modifiedTime: post.updated,
      authors: [`https://${siteURL}/about`],
      images: [
        {
          url: `${post.imageUrl}`,
          width: 1024,
          height: 576,
          alt: post.title,
          type: "image/png"
        }
      ]
    },
    twitter: {
      card: "summary_large_image",
      site: "@meinbiz",
      creator: "@meinbiz",
      title: `${post.title} | FastPocket`,
      description: post.description,
      images: [
        {
          url: `${post.imageUrl}`,
          width: 1024,
          height: 576,
          alt: post.title
        }
      ]
    },
    alternates: {
      canonical: `https://${siteURL}/blogs/${post.slug}`
    }
  }
}

export const generateStaticParams = async () => {
  const posts = await getPostMetadata()
  console.log("static posts", posts.length)
  const mappedPosts = posts.map(post => ({
    slug: post.slug
  }))
  return mappedPosts
}

const PostPage = async props => {
  console.log("params", props.params)
  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
