import { Metadata } from "next";
import { fetchPostById } from "@/api/fetchPostById";
import PostFeedView from "@/components/posts/PostFeedView";
import { buildStorageUrl } from "@/components/main/BaseUrl";
import { Suspense } from "react";
import PageLoader from "@/components/ui/PageLoader";
import { generatePageMetadata } from "@/utils/generatePageMetadata";

type Props = { params: Promise<{ id: string }> };

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { id } = await params;
  const post = await fetchPostById(id);
  const title = post?.caption
    ? `${post.caption.slice(0, 60)} | مدستاگرام`
    : "پست | مدستاگرام";
  const description =
    post?.caption?.slice(0, 160) ||
    "مشاهده پست در مدستاگرام — پلتفرم تخصصی حوزه زیبایی، مدلینگ و عکاسی";
  const ogImage = post?.files?.[0]?.path
    ? buildStorageUrl(post.files[0].path)
    : undefined;

  return generatePageMetadata({
    title,
    description,
    path: `/posts/${id}`,
    type: "article",
    imageUrl: ogImage,
    imageAlt: post?.caption?.slice(0, 80) || "پست مدستاگرام",
  });
}

export default async function PostPage({ params }: Props) {
  const { id } = await params;
  const post = await fetchPostById(id);
  const userId = post?.userId || post?.user_id;

  return (
    <main className="min-h-[100dvh]">
      {post && (
        <script
          type="application/ld+json"
          dangerouslySetInnerHTML={{
            __html: JSON.stringify({
              "@context": "https://schema.org",
              "@type": "SocialMediaPosting",
              headline: post.caption?.slice(0, 110) || "پست مدستاگرام",
              url: `https://modstagram.com/posts/${id}`,
              datePublished: post.createdAt,
              author: {
                "@type": "Person",
                name: `${post.first_name || ""} ${post.last_name || ""}`.trim(),
              },
            }),
          }}
        />
      )}
      <Suspense fallback={<PageLoader className="min-h-[100dvh]" />}>
        <PostFeedView
          initialPostId={id}
          initialPost={post}
          userId={userId}
          showClose
        />
      </Suspense>
    </main>
  );
}
