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

/**
 *
 * @param {object} payloadSearch
 * @param {number} limit
 * @param {number} page
 * @returns {Promise<{listProduct: ShopeeSearchProductGlobal[], totalProduct: number}>}
 */
const searchProductApi = async (payloadSearch = {}, limit = 50, page = 0) => {
  const payloadQuery = {
    order: 'desc',
    by: 'relevancy',
    scenario: 'PAGE_GLOBAL_SEARCH',
    version: 2,
    limit,
    ...payloadSearch,
  };

  if (page) {
    payloadQuery.newest = limit * page;
  }

  if (payloadQuery.page_type === 'search' && payloadQuery.keyword && Number(payloadQuery.newest) >= 500) {
    payloadQuery.scenario = 'PAGE_GLOBAL_SEARCH';
    payloadQuery.version = '2';
    payloadQuery.by = 'relevancy';
  }

  const keyCache = JSON.stringify(payloadQuery);

  const CacheSearch = new CacheShopeeProductSearch(keyCache);

  const getCache = await CacheSearch.get();

  if (getCache) {
    return getCache;
  }

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

  try {
    const fetchUrl = queryString.stringifyUrl({
      url: `${SHOPEE_DOMAIN_HOME}/api/v4/search/search_items`,
      query: payloadQuery,
    });

    const resultSearch = await readyFetchUrlShopeeClient(fetchUrl);

    if (!(resultSearch && resultSearch.items)) {
      return returnSearch;
    }

    returnSearch.listProduct = resultSearch.items.map((item) => {
      return {
        ...item.item_basic,
        ...item,
      };
    });

    returnSearch.totalProduct = resultSearch.total_count;
    await CacheSearch.set(returnSearch);
  } catch (error) {}
  return returnSearch;
};

/**
 *
 * @param {string} categoryId
 * @param {number} limit
 * @param {number} page
 * @returns
 */
export const shopeeSearchProductCategoryId = async (categoryId, limit = 50, page = 0) => {
  const payload = {
    by: 'sales',
    match_id: categoryId,
    order: 'desc',
    page_type: 'search',
    scenario: 'PAGE_CATEGORY',
    source: 'SRP',
  };

  return searchProductApi(payload, limit, page);
};

/**
 *
 * @param {string} keyword
 * @param {number} limit
 * @param {number} page
 * @returns
 */
export const shopeeSearchProductKeyword = (keyword, limit = 50, page = 0) => {
  const payload = {
    keyword,
    page_type: 'search',
    by: 'relevancy',
    order: 'desc',
  };

  return searchProductApi(payload, limit, page);
};

/**
 *
 * @param {string} shopId
 * @param {number} limit
 * @param {number} page
 * @returns
 */
export const shopeeSearchSoldoutShopId = (shopId, limit = 50, page = 0) => {
  const payload = {
    filter_sold_out: 1,
    shopid: shopId,
    match_id: shopId,
    order: 'desc',
    page_type: 'shop',
    sort_by: 'pop',
    use_case: '4',
  };

  return searchProductApi(payload, limit, page);
};
