import { apiShopeeClient } from '@/api/shopee/client/init';
import lodash from 'lodash';
import { CacheShopeeAny } from '@/plugins/store/cache';

export const getKeywordHint = async (keyword) => {
  const payload = {
    extra_params: '',
    historical_query: '',
    keyword,
    search_type: 0,
    version: 1,
  };

  const result = await apiShopeeClient.get('/api/v4/search/search_hint', {
    params: payload,
  });

  return lodash.get(result, 'data.keywords', []);
};

export const getKeywordTrending = async (page = 0, limit = 20) => {
  const payload = {
    limit,
    offset: 0,
  };

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

  const result = await apiShopeeClient.get('/api/v4/search/trending_search', {
    params: payload,
  });

  return lodash.get(result, 'data.queries', []);
};

export const getKeywordSuggest = async (page = 0, limit = 20) => {
  const payload = {
    limit,
    offset: 0,
    bundle: 'popsearch',
  };

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

  const result = await apiShopeeClient.get('/api/v4/search/search_suggestion', {
    params: payload,
  });

  return lodash.get(result, 'data.queries', []);
};

/**
 *
 * @param {number} categoryId
 * @param {number} page
 * @param {number} limit
 * @returns {Promise<{listShop : ShopeeShopMallCategory[], total : number}>}
 */
export const getShopMallCategoryId = async (categoryId, page = 0, limit = 20) => {
  if (!categoryId) {
    throw {
      msg: 'CATEGORY_ID_REQUIRED',
    };
  }

  const payload = {
    category_id: categoryId,
    offset: 0,
    limit,
  };

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

  const CacheStore = new CacheShopeeAny(['shop-mall-catid', JSON.stringify(payload)]);
  const getCache = await CacheStore.get();

  if (getCache) {
    return getCache;
  }

  const result = await apiShopeeClient.get('/api/v4/official_shop/get_shops', {
    params: payload,
  });

  const returnValue = {
    listShop: lodash.get(result, 'data.official_shops', []),
    total: lodash.get(result, 'data.total', 0),
  };

  await CacheStore.set(returnValue);
  return returnValue;
};
