import axios from 'axios';
import ICATPLUS from '../config/icat/icatPlus';
import {
  LOGGED_IN,
  LOGIN_ERROR,
  LOG_IN,
  LOG_OUT,
} from '../constants/actionTypes';
import keycloak from '../config/sso/keycloak';
import ICAT from '../config/icat/icat';

export function doLogOut(params = { expired: false }) {
  return { type: LOG_OUT, ...params };
}

export function doSignIn(plugin, username, password) {
  return (dispatch) => {
    dispatch({ type: LOG_IN, username });

    axios
      .post(`${ICATPLUS.server}/session`, { plugin, username, password })
      .then(({ data }) => {
        if (!data || !data.sessionId) {
          throw new Error('Invalid authentication response');
        }

        const {
          sessionId,
          name,
          fullName,
          isAdministrator,
          lifeTimeMinutes,
        } = data;
        dispatch({
          type: LOGGED_IN,
          sessionId,
          name,
          fullName,
          isAdministrator,
          lifeTimeMinutes,
        });
      })
      .catch((error) => {
        console.error(error);
        dispatch({ type: LOGIN_ERROR, error: 'Authentication failed' });
      });
  };
}

export function doSilentRefreshFromSSO() {
  return (dispatch) => {
    axios
      .post(`${ICATPLUS.server}/session`, {
        plugin: ICAT.authentication.sso.plugin,
        username: null,
        password: keycloak.idToken,
      })
      .then(({ data }) => {
        if (!data || !data.sessionId) {
          throw new Error('Invalid re-authentication response');
        }

        const {
          sessionId,
          name,
          fullName,
          isAdministrator,
          lifeTimeMinutes,
        } = data;
        dispatch({
          type: LOGGED_IN,
          sessionId,
          name,
          fullName,
          isAdministrator,
          lifeTimeMinutes,
        });
      })
      .catch((error) => {
        console.error(error);
        dispatch({ type: LOGIN_ERROR, error: 'Re-authentication failed' });
      });
  };
}
