import listCategory from '@/data/shopee/category/list.json';
import listCategoryV2 from '@/data/shopee/category/v2/input.json';
import categoryTreeHome from '@/data/shopee/category/tree/home.json';
import categoryTreeList from '@/data/shopee/category/tree/list.json';
import { apiShopeeClient } from '@/api/shopee/client/init';

const flattenCategories = (categories) => {
  return categories.flatMap((category) => {
    return [category, ...(Array.isArray(category.children) ? flattenCategories(category.children) : [])];
  });
};

const categoryTreeMap = flattenCategories(categoryTreeHome);
const categoryListV2 = flattenCategories(listCategoryV2);

/**
 *
 * @param {number} categoryId
 * @returns
 */
export const getShopeeCategoryId = (categoryId) => {
  const categoryNumber = Number(categoryId);

  let categoryMatch = listCategory.find((item) => item.id === categoryNumber);

  if (categoryMatch) {
    return categoryMatch;
  }

  categoryMatch = categoryTreeMap.find((item) => item.catid === categoryNumber);

  if (categoryMatch) {
    return categoryMatch;
  }

  categoryMatch = categoryTreeList.find((item) => item.category_id === categoryNumber);

  if (categoryMatch) {
    return categoryMatch;
  }

  categoryMatch = categoryListV2.find((item) => item.id === categoryNumber);

  if (categoryMatch) {
    return categoryMatch;
  }

  return null;
};

export const getCategoryMatchName = (categoryName) => {
  return categoryTreeList.filter((item) => {
    const listName = item.path.map((child) => child.category_name).join(' ');

    return listName.includes(categoryName);
  });
};

export const getShopeeCategoryList = () => listCategory;
export const getShopeeCategoryTreeHome = () => categoryTreeHome;
export const getShopeeCategoryTreeList = () => categoryTreeList;

/**
 *
 * @param {number} categoryId
 * @returns {Promise<ShopeeCategoryTopShop[]>}
 */
export const getListShopCategoryId = async (categoryId) => {
  const result = apiShopeeClient.get('/api/v4/official_shop/get_shops', {
    params: {
      category_id: categoryId,
      limit: 20,
      offset: 0,
    },
  });

  return (await result).data || [];
};
