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

/**
 * @typedef {object} ShopeeSearchReturn
 * @property {ShopeeSearchItemShop[]} listProduct
 * @property {number} totalProduct
 */

/**
 *
 * @param {number} shopId
 * @param {number} limit
 * @param {number} page
 * @returns {Promise<ShopeeSearchReturn>}
 */
const shopeeSearchShopId = async (shopId, limit = 40, page = 0) => {
  const payload = {
    bundle: 'shop_page_category_tab_main',
    shop_id: shopId,
    limit,
    offset: 0,
    upstream: 'pdp',
    step2_upstream: 'dd',
    sort_type: 1,
    item_card_use_scene: 'category_product_list_popular',
    version: 1,
  };

  if (page) {
    payload.offset = limit * page;
  }

  const CacheShop = new CacheShopeeShopSearch(JSON.stringify(payload));

  const getCache = await CacheShop.get();

  if (getCache) {
    return getCache;
  }

  const returnSearch = {
    listProduct: [],
    totalProduct: 0,
  };

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

    const result = await readyFetchUrlShopeeClient(fetchUrl);

    if (!result.data) {
      return returnSearch;
    }

    returnSearch.totalProduct = result.data.total || 0;
    returnSearch.listProduct = result.data.items || [];

    if (returnSearch.totalProduct && returnSearch.listProduct.length) {
      await CacheShop.set(returnSearch);
    }

    return returnSearch;
  } catch (error) {
    return returnSearch;
  }
};

export default shopeeSearchShopId;
