import '@/types/Browser';
import { SHOPEE_DOMAIN_HOME, SHOPEE_DOMAIN_SELLER } from '@/config/api';
import { getAllTab, openExternalUrl } from '@/browser/tab';
import delay from 'delay';

const sellerProductUrl = `${SHOPEE_DOMAIN_SELLER}/portal/product`;

/**
 *
 * @param {string} url
 * @returns {Promise<BrowserTabStore>}
 */
const getTabMatchUrl = async (url) => {
  /** @type {BrowserTabStore[]} */
  const listTab = await getAllTab();
  return listTab.find((tab) => tab.url.includes(url));
};

export const getTabShopeeClientAny = async () => {
  return getTabMatchUrl(SHOPEE_DOMAIN_HOME);
};

export const getTabShopeeSellerAny = async () => {
  return getTabMatchUrl(SHOPEE_DOMAIN_SELLER);
};

export const getTabShopeeSellerProduct = async () => {
  return getTabMatchUrl(sellerProductUrl);
};

export const makeTabShopeeSellerProduct = async () => {
  const tab = await getTabShopeeSellerProduct();

  if (tab) {
    return tab;
  }

  await openExternalUrl(sellerProductUrl, false);

  return new Promise(async (resolve) => {
    await delay(3000);

    getTabShopeeSellerProduct().then((tab) => {
      resolve(tab);
    });

    setTimeout(() => {
      resolve(null);
    }, 50000);
  });
};

export const makeTabShopeeClient = async (loadUrl = '') => {
  const tab = await getTabShopeeClientAny();

  if (tab) {
    return tab;
  }

  await openExternalUrl(loadUrl || SHOPEE_DOMAIN_HOME, false);

  await delay(2000);

  return getTabShopeeClientAny();
};
