import gql from "../api";
import { store} from '../store';
import { actionPromise } from ".";

const actionOrder = () =>
  async (dispatch, getState) => {
      let {cart} = store.getState()
                                                                          //магия по созданию структуры вида
                                                                      //let orderGoods = [{good: {_id}, count}, {good: {_id}, count} .......]
                                                                      //из структуры вида
                                                                          //{_id1: {good, count},
                                                                          //_id2: {good, count}}
      const orderGoods = Object.entries(cart).map(([_id, {good, count}]) => ({good: {_id}, count}))

      await dispatch(actionPromise('order', gql(`
                  mutation newOrder($order:OrderInput){
                    OrderUpsert(order:$order)
                      { _id total 	}
                  }
          `, {order: {orderGoods}})))
}

export default actionOrder;