/*
 * 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 SyliusApiLogin = (el) => {
  const signInButton = el.querySelector('#sylius-api-login-submit');
  const alertContainer = el.querySelector('#sylius-api-validation-error');
  const { url } = signInButton.dataset;
  const emailField = el.querySelector('input[type="email"]');
  const passwordField = el.querySelector('input[type="password"]');
  const csrfTokenField = el.querySelector('input[type="hidden"]');
  const csrfTokenName = csrfTokenField.getAttribute('name');

  signInButton.addEventListener('click', (e) => {
    e.preventDefault();

    const headers = new Headers();
    headers.append('Accept', 'application/json, text/javascript, */*; q=0.01');
    headers.append('X-Requested-With', 'XMLHttpRequest');

    const body = new FormData();
    body.append('_username', emailField.value);
    body.append('_password', passwordField.value);
    body.append([csrfTokenName], csrfTokenField.value);

    fetch(url, {
      method: 'POST', headers, body, redirect: 'manual',
    })
      .then((response) => response.json())
      .then(({ success, message }) => {
        if (success) {
          window.location.reload();
        } else {
          alertContainer.innerHTML = message;
          alertContainer.classList.remove('d-none');
        }
      });
  });
};

export default SyliusApiLogin;
