import { unstable_cache } from 'next/cache'
import { getPayload } from 'payload'
import config from '@/payload.config'
import { Page } from '@/payload-types'

export async function fetchPageBySlug(
  slug: string,
  draft: boolean = false,
): Promise<Page | undefined> {
  const fetchPage = async () => {
    const payload = await getPayload({ config })
    const data = await payload.find({
      collection: 'pages',
      where: {
        slug: {
          equals: slug,
        },
      },
      limit: 1,
      draft,
    })
    return data.docs?.[0] ?? undefined
  }

  if (draft) {
    return fetchPage()
  }

  return unstable_cache(fetchPage, ['pages', slug], {
    tags: ['pages', `pages-${slug}`],
  })()
}
