import { useContext, useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { UserContext } from '../../context/UserContext.jsx';
import { getUserData } from '../../utils/session.js';
import { ROLES } from '../../constants.js';

const TELLER_ROLES = [
    ROLES.ROLE_USER,
    ROLES.ROLE_SUPER_ADMIN,
    ROLES.ROLE_BRANCH_ADMIN,
];

export default function AuthGuard({ children }) {
    const navigate = useNavigate();
    const { user: contextUser } = useContext(UserContext);
    const [allowed, setAllowed] = useState(false);

    useEffect(() => {
        const user = contextUser ?? getUserData();
        const roles = Array.isArray(user?.roles) ? user.roles : [];
        const hasAccess = roles.some((role) => TELLER_ROLES.includes(role));

        if (!user || !hasAccess) {
            setAllowed(false);
            navigate('/login', { replace: true });
            return;
        }

        setAllowed(true);
    }, [contextUser, navigate]);

    if (!allowed) {
        return null;
    }

    return <>{children}</>;
}
