import { PostMessageFetchUrl, PostMessageFetchListener } from '@/bridge/content/postMessage';

const fetchUrlService = async (payload) => {
  const { url, method, body } = payload;

  const fetchUrl = url;

  const payloadFetch = {
    method,
    headers: {
      accept: 'application/json',
      'af-ac-enc-dat': null,
      'af-ac-enc-sz-token': '',
      'content-type': 'application/json',
    },
  };

  if (method === 'POST') {
    payloadFetch.body = JSON.stringify(body);
  }

  const responsive = await fetch(fetchUrl, payloadFetch);

  const json = await responsive.json();

  return json;
};

const listenerFetchData = (callback) => {
  const { fetch: originalFetch } = window;
  window.fetch = async (...args) => {
    const [url, payload] = args;
    const response = await originalFetch(...args);

    if (url.includes('/api/')) {
      const clone = response.clone();

      clone.json().then((json) => {
        callback({
          json,
          url,
          payload,
        });
      });
    }

    return response;
  };
};

const startService = async () => {
  PostMessageFetchUrl.startHandler(fetchUrlService);

  listenerFetchData((payload) => PostMessageFetchListener.sendMessage(payload));
};

startService();
