import React from 'react';
import { Redirect, Route, RouteProps } from 'react-router-dom';

import { getUser } from '../services/auth';

function hasRoles(requiredRoles: string[], userRoles: string[]) {
    requiredRoles = requiredRoles || [];
    userRoles = userRoles || [];

    return requiredRoles.every((role) => userRoles.includes(role));
}

interface Props extends RouteProps {
    component?: React.ComponentType;
    roles?: string[];
}

export default function PrivateRoute({
    component,
    roles,
    render,
    children,
    ...rest
}: Props) {
    return (
        <Route
            {...rest}
            render={(props) => {
                const user = getUser();

                if (!user) {
                    return (
                        <Redirect
                            to={`/login?next=${props.location.pathname || '/'}`}
                        />
                    );
                }

                if (roles && !hasRoles(roles, user?.roles)) {
                    return (
                        <h1>You do not have permission to access this page.</h1>
                    );
                }

                if (component) {
                    return React.createElement(component);
                }

                if (render) {
                    return render(props);
                }

                if (children) {
                    return children;
                }
            }}
        />
    );
}
