import { bridgeTabFetchShopeeUrl } from '@/bridge/content/tab';
import { getAllTab } from '@/browser/tab';
import { makeTabShopeeClient, makeTabShopeeSellerProduct } from '@/bridge/shopee/tab';

const shopeeClientDomain = 'https://shopee.vn';
const shopeeSellerDomain = 'https://banhang.shopee.vn';

const listUrlMatchBlock = ['/verify'];
const listUrlMatchCaptcha = ['/verify/captcha'];

export const readyFetchUrlShopeeClient = async (url = shopeeClientDomain) => {
  const tab = await makeTabShopeeClient();

  if (!tab) {
    return null;
  }

  return bridgeTabFetchShopeeUrl(tab.id, {
    url,
    method: 'GET',
  });
};

export const readyPostUrlShopeeClient = async (url = shopeeClientDomain, payload = {}) => {
  const tab = await makeTabShopeeClient();

  if (!tab) {
    return null;
  }

  return bridgeTabFetchShopeeUrl(tab.id, {
    url,
    body: payload,
    method: 'POST',
  });
};

export const readyPostUrlShopeeSeller = async (url = shopeeSellerDomain, payload = {}) => {
  const tab = await makeTabShopeeSellerProduct();

  if (!tab) {
    return null;
  }

  return bridgeTabFetchShopeeUrl(tab.id, {
    url,
    body: payload,
    method: 'POST',
  });
};

export const getTabIdReadyFetch = async () => {
  const listTabShopee = (await getAllTab()).filter((tabData) => tabData.url.includes(shopeeClientDomain));

  if (!(listTabShopee && listTabShopee.length)) {
    return null;
  }

  const tabValid = listTabShopee.find((tabData) => {
    const isBlock = listUrlMatchBlock.some((urlBlock) => tabData.url.includes(urlBlock));
    const isCaptcha = listUrlMatchCaptcha.some((urlBlock) => tabData.url.includes(urlBlock));
    if (!isBlock && !isCaptcha) {
      return tabData;
    }
  });

  return tabValid;
};

export const getTabIsCaptcha = async () => {
  const listTabShopee = (await getAllTab()).filter((tabData) => tabData.url.includes(shopeeClientDomain));

  return listTabShopee.some((tabData) => {
    const isCaptcha = listUrlMatchCaptcha.some((urlBlock) => tabData.url.includes(urlBlock));

    if (isCaptcha) {
      return true;
    }
  });
};
