// injects the script in the body of the document.
// returns a promise that gets resolves once the script has been loaded in the document
export const injectScript = (url, document = window.document) => {
  const script = document.createElement('script');
  script.src = url;
  script.type = 'text/javascript';
  script.async = true;

  const body = document.getElementsByTagName('body')?.[0] ?? null;
  if (body === null) {
    throw ERR_UNKNOWN;
  }

  return new Promise((resolve, reject) => {
    script.addEventListener('load', () => {
      resolve(script);
    });

    script.addEventListener('error', () => {
      reject(new Error('unable to load translation script'));
    });

    body.appendChild(script);
  });
};