/* eslint-disable prefer-promise-reject-errors */
/* eslint-disable jsdoc/require-jsdoc */
// eslint-disable-next-line no-multiple-empty-lines

async function apiFetchUrl(url, method, postBody = null) {
  const fetchId = `id-${crypto.randomUUID()}`; // uuid

  const fetchElementId = `script-fetch-${fetchId}`;
  const getElementId = `script-get-${fetchId}`;

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

  if (method === 'POST' && postBody) {
    payloadRequest.method = method;
    payloadRequest.body = JSON.stringify(postBody);
  }

  const fetchScript = `
      fetch('${url}', ${JSON.stringify(payloadRequest)})
        .then((res) => res.json())
        .then((product) => {
            const script = document.createElement('script');
            script.type = type="application/json";
            script.id = '${getElementId}'
            script.textContent = JSON.stringify(product);
            document.head.appendChild(script);
        });
  `;

  const scriptFetch = document.createElement('script');
  scriptFetch.type = 'application/javascript';
  scriptFetch.id = fetchElementId;
  scriptFetch.textContent = fetchScript;
  document.head.appendChild(scriptFetch);

  return new Promise((reslove, reject) => {
    setTimeout(() => {
      const scriptGet = document.getElementById(getElementId);

      if (scriptGet) {
        const fetchJson = JSON.parse(scriptGet.textContent);
        reslove(fetchJson);
      } else {
        reject({
          message: 'FETCH_ERROR',
        });
      }

      scriptFetch.remove();
      scriptGet.remove();
    }, 500);
  });
}

apiFetchUrl('https://shopee.vn/api/v4/pdp/get_pc?shop_id=65936410&item_id=21648174425', 'GET', null)
  .then(console.error)
  .catch(console.error);

apiFetchUrl('https://shopee.vn/api/v4/shop/follow', 'POST', {
  shopid: 39232661,
}).then(console.error)
  .catch(console.error);
