import { RESUME_PAYMENT } from '@/store/utils/apiUrls'
import * as T from '@/store/utils/types'
import { get } from '@/store/utils/api'
import _ from 'lodash'
import querystring from 'querystring'
import { getValue } from '@/helpers/variable-handling'

export default {
  namespaced: true,
  state: {
    salesDetails: {},
  },
  getters: {
    getResumePaymentDetails: state => state.salesDetails,
    getSalesCountryId: state => {
      return getValue(state.salesDetails, 'sales_data.country_id', false)
    },
  },
  actions: {
    async retrieveSalesDetails({ commit, dispatch }, payload) {
      commit(T.PROCESSING_STARTED, 'loadingSalesDetails', { root: true })
      let saleId = payload.salesId
      let query = '?' + querystring.stringify(_.pickBy({ signature: payload.signature }, _.identity))
      await get(RESUME_PAYMENT + `/${saleId}` + query)
        .then(response => {
          commit(T.SET_RESUME_PAYMENT_DETAILS, response.data)
          commit(T.SALES_SET_SALE, response.data.sales_data, { root: true })
        })
        .catch(e => {
          dispatch('logError', { FetchSalesDetail: e }, { root: true })
        })
        .finally(() => {
          commit(T.PROCESSING_FINISHED, 'loadingSalesDetails', { root: true })
        })
    },
  },
  mutations: {
    [T.SET_RESUME_PAYMENT_DETAILS](state, data) {
      state.salesDetails = data
    },
  },
}
