'use client'

import { Tenant } from '@/payload-types'
import useGlobal from '@/stores'
import { redirect } from 'next/navigation'
import { AuthResult } from 'node_modules/payload/dist/auth/operations/auth'
import { PaginatedDocs } from 'payload'
import { ReactNode, use, useEffect } from 'react'

type SuspenseProps = {
  getUserPromise: Promise<AuthResult>
  getTenantPromise: Promise<PaginatedDocs<Tenant>>
  children: ReactNode
}
const RootLayoutSuspenseFrontend = (props: SuspenseProps) => {
  const { getUserPromise, getTenantPromise, children } = props

  const { user: authedUser } = use(getUserPromise)
  const foundTenants = use(getTenantPromise)

  const { setUser, setTenant } = useGlobal()

  useEffect(() => {
    try {
      if (!authedUser || !authedUser?.id) return redirect('/login')

      setUser(authedUser)
    } catch (err) {
      return redirect('/login')
    }
  }, [authedUser])

  useEffect(() => {
    try {
      if (!foundTenants?.docs || !foundTenants.docs.length || !foundTenants.docs[0]) {
        return redirect('/')
      }

      setTenant(foundTenants.docs[0])
    } catch (err) {
      return redirect('/')
    }
  }, [foundTenants])

  return <>{children}</>
}

export default RootLayoutSuspenseFrontend
