import React from 'react';
import { Navigate, useLocation, Outlet } from 'react-router-dom';
import { useMsal } from '@azure/msal-react';
import { useUser } from '../context/UserContext.js';
import { permissionTypes } from '../constants/userConstants.js';

function ProtectedRoute() {
  const { accounts } = useMsal();
  const location = useLocation();
  const { permissions } = useUser();

  if (!accounts?.length) {
    return <Navigate to="/signin" />;
  }

  if (permissions === undefined || permissions === null) {
    return null;
  }

  const currentPath = location.pathname;
  const flatPermissions = [];

  permissions.forEach((item) => {
    if (item?.IsSubMenu && Array.isArray(item.SubMenuItems)) {
      flatPermissions.push(...item.SubMenuItems);
    } else {
      flatPermissions.push(item);
    }
  });
  const matchedPermission = flatPermissions.find((item) => item.Path === currentPath || currentPath.includes(item.Path) || currentPath === '/');

  if (!matchedPermission) {
    return <Navigate to="/unauthorized" />;
  }

  const allowed = matchedPermission.Permission_Id === `${permissionTypes[0].key}` || matchedPermission.Permission_Id === `${permissionTypes[1].key}`;

  return allowed ? (
    <Outlet context={{ permissionId: matchedPermission.Permission_Id }} />
  ) : (
    <Navigate to="/unauthorized" />
  );
  
}

export default ProtectedRoute;
