/* eslint-disable no-restricted-syntax */
/* eslint-disable guard-for-in */
import axios from 'axios';

export default {
  namespaced: true,
  state: {
    regions: [],
    detailedRegion: [],
  },
  mutations: {
    setRegions(state, regions) {
      state.regions = regions;
    },
    clearDetailed(state) {
      state.detailedRegion = [];
    },
    addDetailed(state, detailed) {
      state.detailedRegion.push(detailed);
    },
  },
  getters: {},
  actions: {
    getRegions({
      commit,
      dispatch,
    }) {
      axios.get(
        'https://www.tradeunipoint.com/unibackend/seam/resource/rest/products/regions/list/ZA/',
      )
        .then((result) => {
          commit('setRegions', result.data);
          if (result.data) {
            for (const i in result.data) {
              const region = result.data[i];
              dispatch('getDetailedRegion', region);
            }
          }
        })
        .catch(console.error);
    },
    getDetailedRegion({
      commit,
    }, region) {
      if (region) {
        axios
          .get(`https://www.tradeunipoint.com/unibackend/seam/resource/rest/products/resorts/${
            region.regionCode }/`)
          .then(result => commit('addDetailed', {
            id: region.id,
            regionCode: region.regionCode,
            regionName: region.regionName,
            resorts: result.data,
          }))
          .catch(console.error);
      }
    },
  },
};
