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

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());
      // B2Cからもログアウトする
      instance.logout({
        postLogoutRedirectUri: "/?logout=true",
      });
    }
  }, [isAuth, isExpired, dispatch, instance]);

  return component;
};
