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

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

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

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

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

export default async function EditAlbumPage(props: Props) {
  const accessToken = cookies().get("access_token")?.value
  const { albumid } = props.params

  const album = await fetchAlbumDetail(albumid, accessToken)

  if (!album) notFound()
  return <EditAlbumContainer albumDetail={album?.data || {}} revalidate={revalidate} />
}
