import { appConfig } from "@/config/app"
import DetailPostContainer from "./section/DetailPostContainer"
import { notFound } from "next/navigation"
import { cookies, headers } from "next/headers"

type Props = { params: { postid: string } }

const fetchPostDetail: any = async (id: string, accessToken: string) => {
  try {
    const res = await fetch(`${appConfig.apiUrl}/games/posts/${id}`, {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
        Origin: appConfig.appUrl,
        Authorization: "Bearer " + accessToken,
      },
      next: { revalidate: 0 },
    })
    if (!res.ok) throw new Error("Failed to fetch post data")
    return res.json()
  } catch (error) {
    console.error("Error fetching post data:", error)
    return null
  }
}

export async function generateMetadata(props: Props) {
  const { postid } = props.params
  const accessToken =
    headers()
      .get("cookie")
      ?.split("; ")
      .find((c) => c.startsWith("access_token="))
      ?.split("=")[1] || ""
  const detailPost = await fetchPostDetail(postid, accessToken)

  if (!detailPost)
    return {
      title: "404 - Page Not Found",
      description: "The page you are looking for does not exist. Please return to the homepage.",
    }

  return {
    title: detailPost?.title || "Detail Post",
    description: detailPost?.subtitle || "",
    alternates: {
      canonical: `${appConfig.appUrl}/wgn/edit-question/${postid}`,
    },
    keywords: "",
    robots: "index, follow",
    openGraph: {
      title: detailPost?.title || "Detail Post",
      description: detailPost?.subtitle || "",
      url: `${appConfig.apiUrl}/wgn/edit-question/${postid}`,
      siteName: "WIZZOR",
      images: [
        {
          url: detailPost?.thumbnail ? detailPost?.thumbnail : `${appConfig.appUrl}/wizzor_group_2x.png`,
          width: 960,
          height: 630,
          alt: "WIZZOR",
        },
      ],
      type: "website",
    },
    twitter: {
      title: detailPost?.title || "Detail Post",
      description: detailPost?.subtitle || "",
      images: [detailPost?.thumbnail ? detailPost?.thumbnail : `${appConfig.appUrl}/wizzor_group_2x.png`],
      site: "WIZZOR",
    },
  }
}

export default async function DetailBookPage(props: Props) {
  const accessToken = cookies().get("access_token")?.value
  const { postid } = props.params
  const detailPost = await fetchPostDetail(postid, accessToken)

  if (!detailPost) notFound()
  return <DetailPostContainer post={detailPost?.data || null} />
}
