import type { Where } from 'payload/types'

import config from '@payload-config'
import { getPayloadHMR } from '@payloadcms/next/utilities/getPayloadHMR.js'

export const fetchDoc = async <T>(args: {
  collection: string
  depth?: number
  slug?: string
}): Promise<T> => {
  const payload = await getPayloadHMR({ config })
  const { slug, collection, depth = 2 } = args || {}

  const where: Where = {}

  if (slug) {
    where.slug = {
      equals: slug,
    }
  }

  try {
    const { docs } = await payload.find({
      collection,
      depth,
      where,
    })

    if (docs[0]) return docs[0] as T
  } catch (err) {
    console.log('Error fetching doc', err)
  }

  throw new Error('Error fetching doc')
}
