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

export async function fetchParish(slug: string, draft: boolean = false) {
  const payload = await getPayload({ config })
  const result = await payload.find({
    collection: 'parish',
    where: {
      slug: {
        equals: slug,
      },
    },
    draft,
  })
  return result.docs[0] ?? null
}

export const fetchAllParishes = unstable_cache(
  async () => {
    const payload = await getPayload({ config })
    return payload.find({
      collection: 'parish',
      limit: 200,
      sort: 'name',
      select: { id: true, name: true, slug: true },
    })
  },
  ['parishes-all'],
  { tags: ['parishes'], revalidate: 3600 },
)
