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

/**
 *
 * @param {number} productId
 * @param {boolean} isCache
 * @returns {Promise<ShopeeSellerProductDetail>}
 */
export const getShopeeSellerProductId = async (productId, isCache = true) => {
  const CacheProduct = new CacheShopeeSellerProductId(productId);

  if (isCache) {
    const getCache = await CacheProduct.get();

    if (getCache) {
      return getCache;
    }
  }

  const result = await apiShopeeSeller.get('/api/v3/product/get_product_info', {
    params: {
      product_id: productId,
      is_draft: false,
    },
  });

  const product = result.data.product_info;

  if (product) {
    await CacheProduct.set(product);
  }

  return product;
};

/**
 *
 * @param {string} categoryId
 * @returns {Promise<ShopeeProductAttribute[]>}
 */
export const getShopeeAttributeCategoryId = async (categoryId) => {
  const CacheAttribute = new CacheShopeeAtrribute(`category-attribute-${categoryId}`);

  const getCache = await CacheAttribute.get();

  if (getCache) {
    return getCache;
  }

  const result = await apiShopeeSeller.get('/api/v3/category/get_attribute_tree/', {
    params: {
      category_ids: categoryId,
    },
  });

  const listAttribute = lodash.get(result, 'data.list[0].attribute_tree', []);
  await CacheAttribute.set(listAttribute);

  return listAttribute;
};
