import { Metadata } from 'next'
import { Suspense } from 'react'
import { dehydrate, HydrationBoundary, QueryClient } from '@tanstack/react-query'
import { blogSingleQueryOptions, mostVisitedBlogsQueryOptions } from '../hooks/useBlogsData'
import { NextPage } from 'next'
import SingleBlogPage from '../components/SingleBlogPage'
import Loading from './loading'
import { BlogSingleResponse } from '../types/BlogTypes'

interface PageProps {
    params: Promise<{
        id: string
    }>
}

export async function generateMetadata(
    { params }: PageProps
): Promise<Metadata> {
    const { id } = await params
    const queryClient = new QueryClient()

    await queryClient.prefetchQuery(blogSingleQueryOptions(id))
    const blog = queryClient.getQueryData(blogSingleQueryOptions(id).queryKey) as BlogSingleResponse

    return {
        title: 'مجله داناک' + ' | ' + blog.data.blog.metaTitle,
        description: blog.data.blog.metaDescription,
    }
}

const SingleBlog: NextPage<PageProps> = async ({ params }) => {

    const { id } = await params

    return (
        <Suspense fallback={<Loading />}>
            <BlogContent id={id} />
        </Suspense>
    )
}

async function BlogContent({ id }: { id: string }) {
    const queryClient = new QueryClient()

    await Promise.all([
        queryClient.prefetchQuery(blogSingleQueryOptions(id)),
        queryClient.prefetchQuery(mostVisitedBlogsQueryOptions)
    ])

    return (
        <HydrationBoundary state={dehydrate(queryClient)}>
            <SingleBlogPage id={id} />
        </HydrationBoundary>
    )
}

export default SingleBlog