import { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { AppDispatch } from "app/store";
import {
  clearToken,
  isAuthenticatedSelector,
  isTokenExpired,
} from "features/auth";
import { useMsal } from "@azure/msal-react";
import { clearUserInfo } from "features/login";

type RouteAuthGuardProps = {
  component: JSX.Element;
};

export const RouteAuthGuard = (props: RouteAuthGuardProps) => {
  const isAuth = useSelector(isAuthenticatedSelector);
  const isExpired = useSelector(isTokenExpired);
  const dispatch: AppDispatch = useDispatch();
  const { instance } = useMsal();
  const { component } = props;
  // トークンがないor有効期限が切れていたらログアウトしてTopへリダイレクト
  useEffect(() => {
    if (!isAuth || isExpired) {
      dispatch(clearToken());
      dispatch(clearUserInfo());
      // B2Cからもログアウトする
      instance.logoutRedirect({
        postLogoutRedirectUri: "/?logout=true",
      });
    }
  }, [isAuth, isExpired, dispatch, instance]);

  return component;
};
