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

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

export const metadata: Metadata = {
  title: "WGN",
}

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 default async function EditQuestionPage(props: Props) {
  const accessToken = cookies().get("access_token")?.value
  const { id } = props.params
  const post = await fetchPostDetail(id, accessToken)

  if (!post) notFound()

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