import Keycloak from 'keycloak-js';
import ICAT from '../icat/icat';

const keycloak = ICAT.authentication.sso.enabled
  ? new Keycloak(ICAT.authentication.sso.configuration)
  : null;

if (keycloak) {
  keycloak.onTokenExpired = () => {
    // When SSO access token expires, try to refresh it
    // https://www.keycloak.org/docs/latest/securing_apps/#callback-events
    keycloak.updateToken().catch(() => {
      // If session has fully expired or an error occurred, clear expired token completely
      keycloak.clearToken(); // this invokes `onAuthLogout`
    });
  };
}

export default keycloak;
