// src/components/ProtectedRoute.tsx
'use client'

import { usePathname, useRouter } from 'next/navigation'
import { useEffect } from 'react'
import { usePermission } from '@/context/auth/PermissionProvider'
import { useAuth } from '@/hooks'
import FallbackSpinner from '../spinner'
import { AccountType } from '@/types/account-type.enum'

const ProtectedRoute = ({ children, allowedRoles }: { children: React.ReactNode; allowedRoles: AccountType[] }) => {
  const { canAccess, currentRole } = usePermission()
  const { loading } = useAuth()
  const router = useRouter()
  const pathname = usePathname()

  useEffect(() => {
    if (!loading && currentRole !== null && !canAccess(allowedRoles)) {
      router.replace('/unauthorized')
    }
  }, [currentRole, pathname, loading])

  if (loading || currentRole === null) {
    return <FallbackSpinner />
  }

  if (!canAccess(allowedRoles)) {
    return <FallbackSpinner />
  }

  return <>{children}</>
}

export default ProtectedRoute
