import { EVENT_TAB_FETCH_URL, EVENT_TAB_ON_CHANGE } from '@/bridge/config/event';
import { sendMessage } from 'webext-bridge/background';

const isReceivingEndError = (error) => {
  const msg = error?.message ?? '';
  return msg.includes('Receiving end does not exist') || msg.includes('Could not establish connection');
};

const sendMessageTabId = async (tabId, eventName, payloadSend) => {
  const payloadContext = { context: 'content-script', tabId };
  return sendMessage(eventName, payloadSend, payloadContext);
};

/**
 *
 * @param {number} tabId
 * @param {object} payload
 * @param {string} payload.url
 * @param {RequestMethod} payload.method
 * @param {object} [payload.body]
 * @returns
 */
export const bridgeTabFetchShopeeUrl = async (tabId, payload = {}) => {
  try {
    return await sendMessageTabId(tabId, EVENT_TAB_FETCH_URL, payload);
  } catch (error) {
    if (isReceivingEndError(error)) {
      return null;
    }
    throw error;
  }
};

export const bridgeTabOnChange = async (tabId, payload = {}) => {
  try {
    return await sendMessageTabId(tabId, EVENT_TAB_ON_CHANGE, payload);
  } catch (error) {
    if (isReceivingEndError(error)) {
      return null;
    }
    throw error;
  }
};
