import AppRouter from "AppRouter";
import { BrowserRouter } from "react-router-dom";
import { GlobalStyle } from "styles/GlobalStyle";
import { PublicClientApplication } from "@azure/msal-browser";
import { MsalProvider, useMsal } from "@azure/msal-react";
import { msalConfig } from "common/msalConfig";
import { useEffect } from "react";
import { useDispatch } from "react-redux";
import globalAxios, { AxiosError, AxiosResponse } from "axios";
import { clearToken } from "features/auth";

const App = (): JSX.Element => {
  const dispatch = useDispatch();
  const { instance } = useMsal();
  const pca = new PublicClientApplication(msalConfig);
  useEffect(() => {
    const id = globalAxios.interceptors.response.use(
      (response: AxiosResponse) => response,
      (e: AxiosError) => {
        if (e?.response?.status === 401) {
          dispatch(clearToken());
          instance.logout({
            postLogoutRedirectUri: "/",
          });
        }
        return Promise.reject(e);
      }
    );
    const cleanup = () => {
      globalAxios.interceptors.response.eject(id);
    };
    return cleanup;
  }, [dispatch, instance]);

  return (
    <>
      <GlobalStyle />
      <MsalProvider instance={pca}>
        <BrowserRouter>
          <AppRouter />
        </BrowserRouter>
      </MsalProvider>
    </>
  );
};

export default App;
