import { getListShop, getShopWarehouse, refreshToken } from '@/api/autoshopee/tiktok';
import i18n from '@/vue/i18n';

/** @type {VuexStoreModule} */
export const tiktokStore = {
  namespaced: true,

  state() {
    return {
      shop: {
        selected: '',
        list: [],
      },
      warehouse: {
        selected: '',
        list: [],
      },
    };
  },

  mutations: {
    SET_SHOP_SELECT(state, id) {
      state.shop.selected = id;
      state.warehouse.selected = '';
    },

    SET_SHOP_LIST(state, list) {
      state.shop.list = list;
    },

    SET_WAREHOUSE_SELECT(state, id) {
      state.warehouse.selected = id;
    },

    SET_WAREHOUSE_LIST(state, list) {
      state.warehouse.list = list;
    },
  },

  getters: {
    getTiktokShopSelect(state) {
      return state.shop.selected;
    },

    getTiktokShopList(state) {
      return state.shop.list.map((item) => ({
        ...item,
        label: [item.name, item.disconnected ? `(${i18n.t('SHOP_DISCONNECTED')})` : ''].join(' '),
        disabled: item.disconnected,
      }));
    },

    getTiktokWarehouseSelect(state) {
      return state.warehouse.selected;
    },

    getTiktokWarehouseList(state) {
      return state.warehouse.list.filter((item) => item.warehouse_type === 1);
    },
  },

  actions: {
    async TiktokSelectShop({ commit, dispatch }, id) {
      commit('SET_SHOP_SELECT', id);
      await refreshToken(id);
      return dispatch('TiktokGetListWarehouse');
    },

    async TiktokGetListShop({ commit }) {
      const { data: list } = await getListShop();
      commit('SET_SHOP_LIST', list);
    },

    TiktokSelectWarehouse({ commit }, id) {
      commit('SET_WAREHOUSE_SELECT', id);
    },

    async TiktokGetListWarehouse({ commit, getters }) {
      const { data: list } = await getShopWarehouse(getters.getTiktokShopSelect);
      commit('SET_WAREHOUSE_LIST', list);
      return list;
    },
  },
};
