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

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 imagePath = post?.files?.[0]?.path?.replace(
    "/root/modstagram-back/storage",
    ""
  );
  const ogImage = imagePath ? `${IMAGE_BASE_URL}${imagePath}` : undefined;

  return {
    title,
    description,
    alternates: { canonical: `https://modstagram.com/posts/${id}` },
    openGraph: {
      title,
      description,
      url: `https://modstagram.com/posts/${id}`,
      type: "article",
      images: ogImage ? [{ url: ogImage, width: 1080, height: 1350 }] : [],
    },
    twitter: {
      card: "summary_large_image",
      title,
      description,
      images: ogImage ? [ogImage] : [],
    },
    robots: { index: true, follow: true },
  };
}

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}
          userId={userId}
          showClose
        />
      </Suspense>
    </main>
  );
}
