import { useEffect } from "react";
import { useLocation, useNavigate } from "react-router-dom";

import { useAuthorizedContext } from "../contexts/authorized/useAuthorizedContext";
import { Roles } from "../entities/Roles";

const rolePaths = new Map<Roles, string>([
	["Administrator", "admin"],
	["Watcher", "watcher"],
	["Manager", "manager"],
	["Visitor", "visitor"],
]);

export const AuthorizedRedirection = () => {
	const { user } = useAuthorizedContext();
	const navigate = useNavigate();
	const location = useLocation();

	useEffect(() => {
		if (!user) {
			return;
		}

		const path = rolePaths.get(user.role);
		if (!path) {
			throw new Error("Role path not found!");
		}

		if (location.pathname.includes(path)) {
			return;
		}

		navigate(path);
	}, [location.pathname, user]);

	if (!user) {
		throw new Error("User must be defined!");
	}

	return null;
};
