import '@/types/Store/Shopee/Shopee';
import { v4 as uuidv4 } from 'uuid';
import i18n from '@/vue/i18n';
import { EVENT_SHOPEE_PRODUCT_SELECT_VARIANT } from '@/bridge/config/event';
import { getShopeeProductId } from '@/api/shopee/client/product/get';
import { shopeeSetting } from '@/plugins/setting';
import { sendMessage } from 'webext-bridge/popup';
import { getAllTab } from '@/browser/tab';
import { SHOPEE_DOMAIN_HOME } from '@/config/api';
import { loggerShopee } from '@/plugins/logger';

/** @type {VuexStoreModule} */
export const productStore = {
  state() {
    return {
      isLoaded: false,
      name: '',
      description: '',
      detail: {},
      clone: {
        payload: shopeeSetting.cloneProductEditData.get(),
      },
    };
  },
  mutations: {
    /**
     *
     * @param {StoreShopeeProduct} state
     * @param {object} params
     */
    SET_SHOPEE_CLONE_PAYLOAD(state, params) {
      state.clone.payload = params;
      shopeeSetting.cloneProductEditData.set(params);
    },
    /**
     *
     * @param {StoreShopeeProduct} state
     * @param {ShopeeProductData} product
     */
    SET_SHOPEE_PRODUCT(state, product) {
      state.isLoaded = true;
      state.name = product.name;
      state.detail = product;
      document.title = state.name;
    },
    /**
     *
     * @param {StoreShopeeProduct} state
     */
    SET_SHOPEE_PRODUCT_ERROR(state) {
      state.isLoaded = false;
      state.detail.name = i18n.t('PRODUCT_GET_ERROR');
      state.detail.description = i18n.t('PRODUCT_GET_ERROR_REPLOAD_PAGE');
    },
  },
  getters: {
    /**
     *
     * @param {StoreShopeeProduct} state
     */
    getShopeeClonePayload(state) {
      return state.clone.payload;
    },
    /**
     *
     * @param {StoreShopeeProduct} state
     */
    getProductShopee(state) {
      return state.detail;
    },
    /**
     *
     * @param {StoreShopeeProduct} state
     */
    getProductShopeeLoaded(state) {
      return state.isLoaded;
    },
  },
  actions: {
    async ShopeeProductFetchStock({ dispatch }, { productId, shopId }) {
      /** @type {ShopeeProductData} */
      const productData = await getShopeeProductId(productId, shopId, 'popup', true);

      const listNeedFetchStock = productData.models.filter((model) => !model.fetched_stock);

      if (!listNeedFetchStock.length) {
        return false;
      }

      const requestId = uuidv4();

      const listTabShopee = (await getAllTab()).filter(({ url }) => url.includes(SHOPEE_DOMAIN_HOME) && url.includes(productId) && url.includes(shopId));

      const tabId = listTabShopee.length ? listTabShopee[0].id : null;

      if (!tabId) {
        return false;
      }

      const payloadRequest = {
        productId,
        shopId,
        requestId,
        listSelect: listNeedFetchStock.map((item) => ({ titer: (item.extinfo && item.extinfo.tier_index) || [], modelId: item.model_id })),
      };

      sendMessage(EVENT_SHOPEE_PRODUCT_SELECT_VARIANT, payloadRequest, { context: 'content-script', tabId });

      return dispatch('ShopeeGetProduct', { productId, shopId });
    },
    async ShopeeGetProduct({ dispatch, commit }, { productId, shopId }) {
      try {
        /** @type {ShopeeProductData} */
        const productData = await getShopeeProductId(productId, shopId, 'popup', true);

        if (!(productData && productData.name)) {
          throw 'GET_PRODUCT_ERROR';
        }

        commit('SET_SHOPEE_PRODUCT', productData);

        return productData;
      } catch (error) {
        loggerShopee.error({
          msg: 'SHOPEE_GET_PRODUCT_ERROR',
          error,
        });

        commit('SET_SHOPEE_PRODUCT_ERROR');
        dispatch('PushMessageError', i18n.t('PRODUCT_GET_ERROR_REPLOAD_PAGE'));
      }

      return null;
    },
    ShopeeSetClonePayload({ commit }, params) {
      commit('SET_SHOPEE_CLONE_PAYLOAD', params);
    },
  },
};
