import { FC, useEffect } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
import { getToken } from '../config/func'
import { buildPath } from '../helpers/utils'

type ComponentType = FC<any>

const withAuth = (WrappedComponent: ComponentType): ComponentType => {
    const WithAuthComponent: FC<any> = (props) => {
        const navigate = useNavigate()
        const { slug } = useParams()

        useEffect(() => {
            const checkAuth = async () => {
                const token = await getToken()
                if (!token) {
                    const loginPath = buildPath('auth/login', slug)
                    navigate(loginPath)
                }
            }

            checkAuth()
        }, [navigate, slug])

        return <WrappedComponent {...props} />
    }

    WithAuthComponent.displayName = `WithAuth(${WrappedComponent.displayName || WrappedComponent.name || 'Component'})`

    return WithAuthComponent
}

export default withAuth 