import { createUser } from './user';
import { createStudent, fetchStudent } from './student';
import { FETCH_NEW_TOKEN, FETCH_TOKEN, LOGOUT } from '../constants/auth';
import { invalidateAllApiCaches } from '../utils/api';

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) {
    await dispatch(fetchToken(mobile, password));
    await dispatch(fetchStudent());
  };
}

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());
    invalidateAllApiCaches();
    if (history) history.push('/login');
  };
}

export function registerUser(data) {
  return async function (dispatch) {
    const { mobile, authKey, firstName, lastName, gender, password, ...studentData } = data;
    await dispatch(createUser({ mobile, authKey, firstName, lastName, gender, password }));
    await dispatch(createStudent(studentData));
    await dispatch(fetchToken(mobile, password));
  };
}
