import { type Config } from 'src/payload-types'

import configPromise from '@payload-config'
import { getPayload } from 'payload'
import { unstable_cache } from 'next/cache'

type Global = keyof Config['globals']

export async function getGlobal(slug: Global, depth = 0, locale?: 'en' | 'ru' | 'es') {
  const payload = await getPayload({ config: configPromise })

  const global = await payload.findGlobal({
    locale,
    slug,
    depth,
  })

  return global
}

export const getCachedGlobal = (slug: Global, depth = 0, locale: 'en' | 'ru' | 'es') =>
  unstable_cache(() => getGlobal(slug, depth, locale), [slug, locale], {
    tags: [`global_${slug}_${locale}`],
  })
