/*
 * This file is part of the Sylius package.
 *
 * (c) Paweł Jędrzejewski
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

/* eslint-env browser */

const SyliusAddToCart = (el) => {
  const url = el.getAttribute('action');
  const { redirect } = el.dataset;
  const validationElement = el.querySelector('#sylius-cart-validation-error');

  el.addEventListener('submit', (e) => {
    e.preventDefault();

    const formData = new FormData(e.target);

    fetch(url, { method: 'POST', body: formData })
      .then((response) => {
        if (String(response.status).match(/^2.*/)) {
          validationElement.classList.add('d-none');

          if (redirect) {
            window.location.href = redirect;
          }

          return {};
        }

        return response.json();
      })
      .then((data) => {
        if (!data.errors) {
          return;
        }

        validationElement.classList.remove('d-none');
        let validationMessage = '';

        Object.entries(data.errors.errors).forEach(([, message]) => {
          validationMessage += message;
        });

        validationElement.innerHTML = validationMessage;
        el.classList.remove('loading');
      });
  });
};

export default SyliusAddToCart;
