import lodash from 'lodash';
import { apiShopeeSeller } from '@/api/shopee/seller/init';
import { CacheShopeeSellerProductList } from '@/plugins/store/cache';

/**
 *
 * @param {string} keyword
 * @param {number} page
 * @param {number} limit
 * @param {string} type
 * @param {string} cursor
 * @returns {Promise<ShopeeSellerProductSearchReturn>}
 */
export const shopeeSellerSearchProductList = async (keyword = '', page = 1, limit = 20, type = 'name', cursor = '') => {
  const params = {
    page_number: page,
    page_size: limit,
  };

  if (keyword && type) {
    params.keyword = keyword;
    params.search_type = type;
  }

  if (cursor) {
    params.cursor = cursor;
  }

  params.count_list_types = ['sold_out', 'banned', 'deboosted', 'deleted', 'unlisted', 'reviewing'].join(',');

  const result = await apiShopeeSeller.get('/api/v3/mpsku/list/search_product_list', {
    params,
  });

  const listProduct = lodash.get(result, 'data.products', []);

  return {
    listProduct,
    cursor: lodash.get(result, 'data.page_info.cursor', ''),
    total: lodash.get(result, 'data.page_info.total', 0),
    count: listProduct.length,
  };
};

/**
 *
 * @param {number} page
 * @param {number} limit
 * @param {string} cursor
 * @returns {Promise<ShopeeSellerProductSearchReturn>}
 */
export const shopeeSellerFetchProductList = async (page = 1, limit = 20, cursor = '') => {
  const keyword = '';
  const type = 'name';

  const CacheProduct = new CacheShopeeSellerProductList([page, limit, cursor].join('-'));

  const getCache = await CacheProduct.get();

  if (getCache) {
    return getCache;
  }

  const result = await shopeeSellerSearchProductList(keyword, page, limit, type, cursor);

  if (result.listProduct.length) {
    await CacheProduct.set(result);
  }

  return result;
};
