import { getPostBySlug } from "@/services/posts";
import { getOrigin } from "@/models/helper";
import { notFound } from "next/navigation";
import { description as defaultDescription } from "@/config/default";
import React from "react";
import Script from "next/script";
import RichContent from "@/components/web/RichContent/rich.content";
import { getGeneralSettings } from "@/models/settings";

// generate metadata
export async function generateMetadata({ params }) {
  const param = await params;
  const slug = param.slug;
  const post = await getPostBySlug(slug);

  let description = await getGeneralSettings();

  if (!description) description = defaultDescription;

  return {
    title: post.metadata.title + " - " + description.title,
    description: post.metadata.description,
    openGraph: {
      title: post.metadata.title,
      description: post.metadata.description,
      images: post.metadata.imagedata.url,
      type: "article",
      tags: post.tags.map((tag) => tag.name),
    },
  };
}

const PostContent = async ({ params }) => {
  const param = await params;
  const slug = param.slug;
  const post = await getPostBySlug(slug);
  const origin = await getOrigin();

  if (!post) return notFound();

  return (
    <>
      {/* JSON-LD */}
      <Script
        id="jsonld"
        type="application/ld+json"
        dangerouslySetInnerHTML={{
          __html: JSON.stringify(
            {
              "@context": "https://schema.org",
              "@type": "Article",
              headline: post.metadata.title,
              alternativeHeadline: post.title,
              image: post.metadata.imagedata.url,
              author: "Arena Wisata",
              keywords: post.tags.map((tag) => tag.name),
              url: origin,
              datePublihed: post.createdAt,
              dateCreated: post.createdAt,
              dateModified: post.modifiedAt,
            },
            null,
            2
          ),
        }}
      />

      {/* Post Component */}
      <>
        {post.title}
        <RichContent html={post.content} />
      </>
    </>
  );
};

export default PostContent;
