import configPromise from '@payload-config'
import { getPayload, PaginatedDocs } from 'payload'
import { headers as getHeaders } from 'next/headers.js'
import { ReactNode, Suspense } from 'react'
import RootLayoutSuspenseFrontend from './layout.suspense'
import { Tenant } from '@/payload-types'

export const metadata = {
  title: 'Next.js',
  description: 'Generated by Next.js',
}

type Props = {
  params: Promise<{
    tenant?: string
  }>
  children: ReactNode
}

const RootLayoutFrontend = async (props: Props) => {
  const { params, children } = props
  const { tenant: tenantSlug } = await params

  const payload = await getPayload({ config: configPromise })
  const headers = await getHeaders()

  const getUserPromise = payload.auth({ headers })

  const getTenantPromise = payload.find({
    collection: 'tenants',
    limit: 1,
    select: {
      name: true,
      domain: true,
      slug: true,
    },
    where: {
      slug: {
        equals: tenantSlug,
      },
    },
  }) as Promise<PaginatedDocs<Tenant>>

  return (
    <html lang="en">
      <body>
        <Suspense fallback={<p>Loading layout...</p>}>
          <RootLayoutSuspenseFrontend
            getUserPromise={getUserPromise}
            getTenantPromise={getTenantPromise}
          >
            {children}
          </RootLayoutSuspenseFrontend>
        </Suspense>
      </body>
    </html>
  )
}

export default RootLayoutFrontend
