import { sendMessage } from 'webext-bridge/options';
import { EVENT_SHOPEE_GET_PRODUCT, EVENT_TAB_GET_WEBCONTENT_HTML, EVENT_TAB_CREATE_BLOB_URL } from '@/bridge/config/event';

const getCurrentTabId = async () => {
  const [tabData] = await chrome.tabs.query({ active: true, currentWindow: true });
  return tabData.id;
};

/**
 *
 * @param {number} tabId
 * @returns {Promise<string>}
 */
export const bridgeGetWebcontentTabId = async (tabId) => {
  return sendMessage(EVENT_TAB_GET_WEBCONTENT_HTML, null, { context: 'content-script', tabId });
};

/**
 *
 * @param {{buffer:Buffer, type:string}}payload
 * @param {number} tabId
 * @returns {Promise<string>}
 */
export const bridgeCreateBlobUrlTabId = async (payload, tabId) => {
  return sendMessage(EVENT_TAB_CREATE_BLOB_URL, payload, { context: 'content-script', tabId });
};

/**
 *
 * @param {{buffer:Buffer, type:string}}payload
 * @returns {Promise<string>}
 */
export const bridgeCreateBlobUrlTabCurrent = async (payload) => {
  const tabId = await getCurrentTabId();
  return bridgeCreateBlobUrlTabId(payload, tabId);
};

export const bridgeGetWebcontentTabCurrent = async () => {
  const tabId = await getCurrentTabId();
  return bridgeGetWebcontentTabId(tabId);
};

/**
 *
 * @param {BridgeShopeeGetProduct}payload
 * @returns {Promise<ShopeeProductData>}
 */
export const bridgeShopeeGetProduct = async (payload) => sendMessage(EVENT_SHOPEE_GET_PRODUCT, payload);
