import * as types from './types';

import devcms from '@devcms/sdk';

const loginSuccess = user => ({
  type: types.AUTH_LOGIN_SUCCESS,
  user: user,
});

const loginError = error => ({
  type: types.AUTH_LOGIN_ERROR,
  error: error,
});

const login = (email, password) => {
  return (dispatch) => devcms.admin.auth.login(email, password)
    .then(user => dispatch(loginSuccess(user)))
    .catch(error => {
      dispatch(loginError(error));

      throw error;
    });
};

const logout = () => {
  return (dispatch) => devcms.admin.auth.logout()
    .then(() => dispatch({ type: types.AUTH_LOGOUT_SUCCESS }));
};

const currentUser = () => {
  return (dispatch) => devcms.admin.auth.me()
    .then(user => dispatch(loginSuccess(user)))
    .catch(error => dispatch(loginError(error)));
};

export { currentUser, login , logout };
