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

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

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

const fetchMarketDetail: any = async (id: string, accessToken: string) => {
  try {
    const res = await fetch(`${appConfig.apiUrl}/fleamarket/items/${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 market data")
    return res.json()
  } catch (error) {
    console.error("Error fetching market data:", error)
    return null
  }
}

const revalidate=async ( id: string ) => {
  'use server';
  revalidatePath( `${appConfig.apiUrl}/fleamarket/items/${id}` );
};

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

  if (!market) notFound()
  return <DetailPostMarketContainer marketDetail={market?.data || {}} revalidate={revalidate} />
}
