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

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

type Global = keyof Config['globals']

async function getGlobal(slug: Global, depth = 0) {
  const payload = await getPayload({ config: configPromise })

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

  return global
}

/**
 * Returns a unstable_cache function mapped with the cache tag for the slug
 */

export const getCachedGlobal = <T extends GlobalSlug>(slug: T, depth = 0) =>
  unstable_cache(
    async (): Promise<DataFromGlobalSlug<T>> => {
      const payload = await getPayload({ config: configPromise })

      return payload.findGlobal({
        slug,
        depth,
      })
    },
    [slug],
    {
      tags: [`global_${slug}`],
    },
  )
