import { HeaderClient } from './Component.client'
import { getCachedGlobal } from '@/utilities/getGlobals'
import configPromise from '@payload-config'
import { getPayload } from 'payload'
import { unstable_cache } from 'next/cache'
import React from 'react'

const getCachedNavCategories = unstable_cache(
  async () => {
    try {
      const payload = await getPayload({ config: configPromise })

      const [parentsResult, childrenResult] = await Promise.all([
        payload.find({
          collection: 'categories',
          where: { parent: { exists: false } },
          sort: 'order',
          limit: 100,
          depth: 0,
          draft: false,
        }),
        payload.find({
          collection: 'categories',
          where: { parent: { exists: true } },
          sort: 'order',
          limit: 500,
          depth: 1,
          draft: false,
        }),
      ])

      return {
        parents: parentsResult.docs as any[],
        children: childrenResult.docs as any[],
      }
    } catch {
      return { parents: [], children: [] }
    }
  },
  ['nav-categories'],
  { tags: ['categories'], revalidate: 600 },
)

export async function Header() {
  const [headerData, categories] = await Promise.all([
    getCachedGlobal('header', 1)().catch(() => null),
    getCachedNavCategories().catch(() => ({ parents: [], children: [] })),
  ])

  return <HeaderClient data={headerData} categories={categories} />
}
