import _ from 'lodash'
import querystring from 'querystring'
import * as U from '@/store/utils/apiUrls'
import { get, post } from '@/store/utils/api'
import { getValue } from '@/helpers/variable-handling'
import { PROCESSING_STARTED, PROCESSING_FINISHED } from '@/store/utils/types'
import { SET_I_TOKEN_COUNTRY, SET_I_TOKEN_REDEMPTION_FORM } from '@/store/utils/types'

export const loadITokenVoucherList = async ({ commit }, payload) => {
  commit(PROCESSING_STARTED, 'loadingITokenVoucherList', { root: true })

  let query = '?' + querystring.stringify(_.pickBy(payload, _.identity()))

  return get(U.I_TOKEN_GET_VOUCHER_LIST + query)
    .then(response => response.data)
    .catch(() => false)
    .finally(() => {
      commit(PROCESSING_FINISHED, 'loadingITokenVoucherList', { root: true })
    })
}

export const loadITokenVoucherDetails = async ({ commit }, voucherId) => {
  commit(PROCESSING_STARTED, 'loadingITokenVoucherDetails', { root: true })

  return get(U.I_TOKEN_GET_VOUCHER_DETAILS + voucherId)
    .then(response => {
      let countryId = getValue(response, 'data.campaign.country_id')

      commit(SET_I_TOKEN_COUNTRY, countryId)
      return countryId && response.data
    })
    .catch(() => false)
    .finally(() => {
      commit(PROCESSING_FINISHED, 'loadingITokenVoucherDetails', { root: true })
    })
}

export const updateRedemptionFormData = async ({ commit, getters }, payload) => {
  commit(PROCESSING_STARTED, 'updatingITokenRedemptionForm', { root: true })

  let data = {
    cart: payload.cart || getters.getITokenRedemptionFormDetails.cart || [],
    shippingInfo: payload.shippingInfo || {},
    transactionId: payload.transactionId || false,
  }

  commit(SET_I_TOKEN_REDEMPTION_FORM, data)
  commit(PROCESSING_FINISHED, 'updatingITokenRedemptionForm', { root: true })
}

export const addProductToRedemptionCart = async ({ commit, dispatch, getters }, payload) => {
  commit(PROCESSING_STARTED, 'redeemProductsAddingToCart', { root: true })

  let cartItems = _.cloneDeep(getters.getITokenRedemptionFormDetails.cart || [])
  let startIndex = cartItems.findIndex(product => product.id === payload.id && product.type === payload.type)

  if (startIndex !== -1) {
    if (payload.quantity > 0) {
      cartItems[startIndex].quantity = payload.quantity
    } else {
      cartItems.splice(startIndex, 1)
    }
  } else if (payload.quantity > 0) {
    cartItems.push(payload)
  }
  await dispatch('updateRedemptionFormData', { cart: cartItems })
  commit(PROCESSING_FINISHED, 'redeemProductsAddingToCart', { root: true })
}

export const loadITokenRedemptionChargesStatement = async ({ commit, dispatch }, payload) => {
  commit(PROCESSING_STARTED, 'loadingITokenRedemptionCharges', { root: true })
  let cancelToken = await dispatch('generateCancelToken', 'iTokenShippingCharges', { root: true })
  payload = {
    voucher_id: payload.voucherId,
    campaign_selection: payload.selectedProducts.map(item => ({
      id: item.id,
      type: item.type,
      quantity: item.quantity,
    })),
    address: getValue(payload, 'shippingInfo.recipient_addresses[0]', null),
  }

  return await post(U.I_TOKEN_GET_REDEMPTION_CHARGES, payload, cancelToken.token)
    .then(response => response.data)
    .catch(() => false)
    .finally(() => {
      commit(PROCESSING_FINISHED, 'loadingITokenRedemptionCharges', { root: true })
    })
}

export const createITokenRedemption = async ({ commit, dispatch, getters, rootGetters }, payload) => {
  commit(PROCESSING_STARTED, 'creatingITokenRedemption', { root: true })

  payload = {
    items: payload.items.map(item => ({ id: item.id, type: item.type, quantity: item.quantity })),
    shipping: payload.shipping,
    voucher_id: payload.voucherId,
    country_id: rootGetters.getAppLocationCountry.countryId,
    location_id: rootGetters.getAppLocationCountry.locationId,
  }

  return await post(U.I_TOKEN_CREATE_REDEMPTION, payload)
    .then(async response => {
      let result = response.data.data

      await dispatch('updateRedemptionFormData', {
        ...getters.getITokenRedemptionFormDetails,
        transactionId: result.id,
      })

      if (Number.isInteger(result.sale_id)) {
        await dispatch('setCurrentSaleId', result.sale_id, { root: true })
      }

      return result
    })
    .catch(() => false)
    .finally(() => {
      commit(PROCESSING_FINISHED, 'creatingITokenRedemption', { root: true })
    })
}

export const loadITokenRedemptionDetails = async ({ commit }, transactionId) => {
  commit(PROCESSING_STARTED, 'loadingITokenRedemptionDetails', { root: true })

  return await get(U.I_TOKEN_GET_REDEMPTION_DETAILS + transactionId)
    .then(response => response.data.data)
    .catch(() => false)
    .finally(() => {
      commit(PROCESSING_FINISHED, 'loadingITokenRedemptionDetails', { root: true })
    })
}
