import queryString from 'query-string';
import { readyFetchUrlShopeeClient } from '@/bridge/shopee/api';
import { SHOPEE_DOMAIN_HOME } from '@/config/api';
import { CacheShopeeShop } from '@/plugins/store/cache';
import { excuteFetchUrl } from '@/api/shopee/fetch';

const shopApiMethod = {
  popup: async (url) => {
    return readyFetchUrlShopeeClient(url);
  },
  content: async (url) => {
    return excuteFetchUrl(url);
  },
};

/**
 *
 * @param {number} shopId
 * @param  {ShopeeFetchMethod} method
 * @returns {Promise<ShopeeShopId>}
 */
const getShopeeShopId = async (shopId, method) => {
  if (!method) {
    method = 'popup';
  }

  const CacheShop = new CacheShopeeShop(shopId);

  const getCache = await CacheShop.get();

  if (getCache) {
    return getCache;
  }
  const payload = {
    entry_point: 'ShopByPDP',
    need_cancel_rate: true,
    request_source: 'shop_home_page',
    shopid: shopId,
    version: 1,
  };

  const fetchUrl = queryString.stringifyUrl({
    url: `${SHOPEE_DOMAIN_HOME}/api/v4/shop/get_shop_base`,
    query: payload,
  });

  const result = await shopApiMethod[method](fetchUrl);

  if (result.data) {
    await CacheShop.set(result.data);
  }

  return result.data;
};

export default getShopeeShopId;
