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 {string} username
 * @param  {ShopeeFetchMethod} method
 * @returns {Promise<ShopeeShopId>}
 */
const getShopeeShopByUsername = async (username, method) => {
  if (!method) {
    method = 'popup';
  }

  const CacheShop = new CacheShopeeShop(username);

  const getCache = await CacheShop.get();

  if (getCache) {
    return getCache;
  }
  const payload = {
    entry_point: 'ShopByPDP',
    need_cancel_rate: true,
    request_source: 'shop_home_page',
    username,
    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 getShopeeShopByUsername;
