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

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

const fetchPostCategory: any = async (id: string, accessToken: string) => {
  try {
    const res = await fetch(`${appConfig.apiUrl}/news/local/${id}`, {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
        Authorization: "Bearer " + accessToken,
      },
      cache: "no-store",
    })
    if (!res.ok) return null
    return res.json()
  } catch (error) {
    console.error("Error fetching new data:", error)
    return null
  }
}

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

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

  return {
    title: postCategory?.title || "",
    description: postCategory?.excerpt || "",
    alternates: {
      canonical: `${appConfig.appUrl}/news/${id}`,
    },
    robots: "index, follow",
    openGraph: {
      title: postCategory?.title || "",
      description: postCategory?.excerpt || "",
      url: `${appConfig.apiUrl}/news/${id}`,
      images: [
        {
          url: postCategory?.thumbnail ? postCategory?.thumbnail : `${appConfig.appUrl}/wizzor_group_2x.png`,
          width: 960,
          height: 630,
          alt: "WIZZOR",
        },
      ],
    },
    twitter: {
      title: postCategory?.title || "",
      description: postCategory?.excerpt || "",
      images: [postCategory?.thumbnail ? postCategory?.thumbnail : `${appConfig.appUrl}/wizzor_group_2x.png`],
    },
  }
}

export default async function NewDetailPage(props: Props) {
  const accessToken = cookies().get("access_token")?.value
  const { id } = props.params
  const postCategory = await fetchPostCategory(id, accessToken)

  if (!postCategory) {
    notFound()
  }

  return <NewDetailContainer post={postCategory?.data || null} />
}
