import queryString from 'query-string';
import { getRequestProductSearch, checkCrawlerDetected } from '@/api/shopee/getter';
import { SHOPEE_DOMAIN_HOME } from '@/config/api';
import { CacheShopeeReview } from '@/plugins/store/cache';
import { excuteFetchUrl, fetchJson } from '@/api/shopee/fetch';
import { apiShopeeClient } from '@/api/shopee/client/init';
import { readyFetchUrlShopeeClient } from '@/bridge/shopee/api';
import { getShopeeProductId } from './get';
import { loggerShopee } from '@/plugins/logger';

export { getShopeeProductId };

const fetchSearchKeywordProduct = async (payload = {}) => {
  const fetchUrl = queryString.stringifyUrl({
    url: `${SHOPEE_DOMAIN_HOME}/api/v4/search/search_items`,
    query: payload,
  });

  const fetchSearch = await excuteFetchUrl(fetchUrl);

  if (!(fetchSearch && fetchSearch.items)) {
    return null;
  }

  return fetchSearch;
};

export const getSearchKeywordProduct = async (keyword, page = 0, limit = 60, opts = {}) => {
  const payload = {
    by: 'relevancy',
    keyword,
    limit,
    newest: 0,
    order: 'desc',
    page_type: 'search',
    scenario: 'PAGE_GLOBAL_SEARCH',
    version: 2,
    ...opts,
  };

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

  payload.newest = (payload.newest || 0).toString();
  payload.limit = (payload.limit || 0).toString();

  let resultSearch = null;

  if (false) {
    resultSearch = await fetchSearchKeywordProduct(payload);
  }

  if (!resultSearch) {
    const { active, headers, url } = await getRequestProductSearch(payload);

    if (!active) {
      return null;
    }

    resultSearch = await fetchJson(url, headers);
  }

  if (checkCrawlerDetected(resultSearch)) {
    loggerShopee.error({
      msg: 'CRAWLER_DETECT_PRODUCT',
      search: resultSearch,
      payload,
    });
  }

  return resultSearch;
};

/**
 *
 * @param {string} productId
 * @param {string} shopId
 * @param {number} limit
 * @param {number} page
 * @param {number} filter
 * @param {number} type
 * @returns {Promise<ShopeeProductReview>}
 */
export const getShopeeProductListReview = async (productId, shopId, limit = 10, page = 0, filter = 0, type = 0) => {
  try {
    const payload = {
      itemid: productId,
      shopid: shopId,
      limit,
      offset: page * limit,
      filter,
      filter_size: 0,
      flag: 1,
      exclude_filter: 1,
      fold_filter: 0,
      relevant_reviews: false,
      request_source: 2,
      type,
      tag_filter: '',
      variation_filters: '',
    };

    const CacheReview = new CacheShopeeReview(Object.values(payload).join('-'));

    const getCache = await CacheReview.get();

    if (getCache) {
      return getCache;
    }

    if (false) {
      const fetchReview = await apiShopeeClient.get('/api/v2/item/get_ratings', {
        params: payload,
      });

      await CacheReview.set(fetchReview.data);

      return fetchReview.data;
    }

    const fetchUrl = queryString.stringifyUrl({
      url: `${SHOPEE_DOMAIN_HOME}/api/v2/item/get_ratings`,
      query: payload,
    });

    const fetchReview = await readyFetchUrlShopeeClient(fetchUrl);

    if (!(fetchReview && fetchReview.data)) {
      return null;
    }

    await CacheReview.set(fetchReview.data);

    return fetchReview.data;
  } catch (error) {
    return null;
  }
};
