import { bridgeShopeeGetHeaderProduct } from '@/bridge/content/background';

export const getBaseHeader = () => {
  return {
    'content-type': 'application/json',
  };
};

export const getRequestProductId = async (productId, shopId) => {
  const listHeader = await bridgeShopeeGetHeaderProduct('product');

  const matchProduct = (item) => item.query && item.query.item_id && Number(item.query.item_id) === Number(productId) && Number(item.query.shop_id) === Number(shopId);

  const listPayload = listHeader.filter((item) => matchProduct(item));

  if (!(listPayload && listPayload.length)) {
    return {
      active: false,
      listPayload: [],
    };
  }

  return {
    active: true,
    listPayload,
  };
};

export const getRequestProductSearch = async (payload) => {
  const listPayloadSearch = await bridgeShopeeGetHeaderProduct('search');

  const listKeyPair = ['by', 'keyword', 'newest', 'limit'];

  const matchSearch = (item) => {
    if (!(item.query && item.query.keyword)) {
      return false;
    }
    const matchAll = listKeyPair.every((key) => payload[key] === item.query[key]);

    return matchAll;
  };

  const listMatch = listPayloadSearch.filter((item) => matchSearch(item));

  if (!(listMatch && listMatch.length)) {
    return {
      active: false,
      uuid: '',
      headers: {},
      url: '',
    };
  }

  return {
    active: true,
    ...listMatch[listMatch.length - 1],
  };
};

export const checkCrawlerDetected = (result) => {
  if (result && result['3']) {
    result.error = result['3'];
  }
  return !!(result && result.error && [90309999].includes(result.error));
};
