import {
  CREATE_ORDER,
  FETCH_ORDER,
  UPDATE_ORDER_CODE,
  UPDATE_ORDER_TO_PAY_FROM_CREDIT
} from '../constants/order';

export function fetchOrder(orderId) {
  return {
    type: FETCH_ORDER,
    api: true,
    auth: true,
    payload: {
      method: 'GET',
      url: `/transactions/orders/${orderId}`
    }
  };
}

export function createOrder() {
  return function (dispatch, getState) {
    return dispatch({
      type: CREATE_ORDER,
      api: true,
      auth: true,
      payload: {
        method: 'POST',
        url: '/transactions/orders',
        data: { decks: getState().cart.map(deck => deck.id) }
      }
    });
  };
}

export function payOrderFromCredit(orderId) {
  return {
    type: UPDATE_ORDER_TO_PAY_FROM_CREDIT,
    api: true,
    auth: true,
    payload: {
      method: 'PATCH',
      url: `/transactions/orders/${orderId}/pay-from-credit`,
      data: {}
    }
  };
}

export function updateOrderCode(orderId, codeText) {
  return {
    type: UPDATE_ORDER_CODE,
    api: true,
    auth: true,
    payload: {
      method: 'PATCH',
      url: `/transactions/orders/${orderId}`,
      data: { codeText }
    }
  };
}
