'use client'

// Type Imports
import type { Locale } from '@configs/i18n'
import type { ChildrenType } from '@core/types'
import { useEffect } from 'react'
import { useAuth } from '../contexts/authContext'

// Component Imports
import { redirect } from 'next/navigation'
import Loading from '../components/layout/shared/Loading'
import { getLocalizedUrl } from '../utils/i18n'

export default function RolesGuard({ children, locale }: ChildrenType & { locale: Locale }) {
  const { isAuthenticated, currentUser } = useAuth()

  useEffect(() => {
    if (!isAuthenticated) {
      redirect(getLocalizedUrl('/login', locale))
    }

    if (currentUser?.role !== 'superadmin') {
      redirect(getLocalizedUrl('/not-found', locale))
    }
  }, [isAuthenticated, currentUser])

  return <>{isAuthenticated && currentUser?.role === 'superadmin' ? children : <Loading />}</>
}
