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

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

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