import { Location } from 'history'
import { memo, ReactNode } from 'react'
import { Redirect, Route, RouteProps } from 'react-router-dom'
import { join } from 'path'

import { isURLAvailable } from '@utils/permissions'

export type PrivateRouteProps = RouteProps & {
    root: string
    path: string
    children?: ReactNode
    redirect?: (location?: Location<unknown>) => ReactNode
}

export const defaultRedirect = (location?: Location<unknown>) => (
    <Redirect to={{ pathname: '/access_denied', state: { from: location } }} />
)

export const PrivateRoute = memo<PrivateRouteProps>(({ root = '', path, component, children, redirect = defaultRedirect, ...other }) => {
    const available = isURLAvailable(join(root, path))

    return (
        <Route
            {...other}
            path={path}
            component={available ? component : undefined}
            render={({ location }) => available ? children : redirect(location)}
        />
    )
})

export default PrivateRoute
