import { fetchUserData } from './user';
import { FETCH_NEW_TOKEN, FETCH_TOKEN, LOGOUT } from '../constants/auth';

export function fetchToken(mobile, password) {
  return {
    type: FETCH_TOKEN,
    api: true,
    payload: {
      method: 'POST',
      url: '/auth/login',
      data: { mobile, password }
    }
  };
}

export function loginUser(mobile, password) {
  return async function (dispatch) {
    const { error } = await dispatch(fetchToken(mobile, password));
    if (!error) await dispatch(fetchUserData());
  };
}

export function fetchNewToken(refreshToken) {
  return {
    type: FETCH_NEW_TOKEN,
    api: true,
    payload: {
      method: 'POST',
      url: '/auth/refresh',
      data: { refresh: refreshToken }
    }
  };
}

function requestLogout() {
  return { type: LOGOUT };
}

export function logoutUser(history = null) {
  return function (dispatch) {
    dispatch(requestLogout());
    if (history) history.push('/login');
  };
}
