(function () {
  const CHANNEL_FETCH_BLOB_REQUEST = 'ATSP_TT_FETCH_BLOB_REQUEST';
  const CHANNEL_FETCH_BLOB_REPLY = 'ATSP_TT_FETCH_BLOB_REPLY';

  const fetchBlobService = async (payload) => {
    const { url } = payload;

    const response = await fetch(url, {
      method: 'GET',
      credentials: 'include',
      referrer: 'https://www.tiktok.com/',
    });

    if (!response.ok) {
      throw new Error('FETCH_BLOB_FAILED');
    }

    return response.blob();
  };

  window.addEventListener('message', (event) => {
    if (event.source !== window) {
      return;
    }

    const data = event.data;

    if (!data || data.channelRequest !== CHANNEL_FETCH_BLOB_REQUEST) {
      return;
    }

    const { messageId, payload } = data;

    fetchBlobService(payload)
      .then((blob) => {
        window.postMessage({
          channelReply: CHANNEL_FETCH_BLOB_REPLY, messageId, blob, ok: true,
        }, '*');
      })
      .catch(() => {
        window.postMessage({
          channelReply: CHANNEL_FETCH_BLOB_REPLY, messageId, blob: null, ok: false,
        }, '*');
      });
  });
}());
