import { onMessage } from 'webext-bridge/content-script';
import { EVENT_TAB_FETCH_URL } from '@/bridge/config/event';
import { runtimeOnMessage } from '@/browser/utils';
import { excuteFetchUrl } from '@/api/shopee/fetch';
import { browserSendMessage } from '@/browser/api';
import { PostMessageFetchUrl, PostMessageFetchListener } from '@/bridge/content/postMessage';
import { bridgeShopeeListenFetch } from '@/bridge/content/background';

export const listenerFetch = async () => {
  onMessage(EVENT_TAB_FETCH_URL, async ({ data }) => {
    try {
      const fetchJson = await PostMessageFetchUrl.sendMessage(data);

      return fetchJson;
    } catch (error) {
      return null;
    }
  });

  runtimeOnMessage(async (request, sender, sendResponse) => {
    if (!(request.event && request.event === EVENT_TAB_FETCH_URL && request.data && request.data.url)) {
      sendResponse(true);
      return true;
    }

    try {
      let fetchJson = await PostMessageFetchUrl.sendMessage(request.data);

      if (false) {
        fetchJson = await excuteFetchUrl(request.data);
      }

      /** @type {BridgeSentPayload} */
      const payloadSend = {
        _id: request._id,
        event: request.event,
        payload: request.data,
        data: fetchJson,
        isReturned: true,
      };

      browserSendMessage(payloadSend);

      sendResponse(fetchJson);

      return fetchJson;
    } catch (error) {
      sendResponse(null);
      return null;
    }
  });

  PostMessageFetchListener.startHandler(bridgeShopeeListenFetch);
};
