class Content {
  static get JSON () {
    return 'application/json';
  }
}

class API {
  static get REJECT_URL () {
    return `/api/envelope/reject`;
  }

  static get REJECT_REDIR_URL(){
    return `/envelopekey/${API.ENV_KEY}/rejected`;
  }

  static __XSRF_TOKEN
  static get XSRF_TOKEN() {
    API.__XSRF_TOKEN ??= document.getElementsByName('__RequestVerificationToken')[0].value;
    return API.__XSRF_TOKEN;
  }

  static get ENV_KEY(){
    return ENV_KEY ?? document.querySelector('meta[name="env-key"]').getAttribute('content');
  }
}

const submitForm = async form => await fetch(form.action, {
  method: form.method,
  body: new FormData(form),
  headers: {
      "X-Requested-With": "XMLHttpRequest"
  }
})

const createRequest = async (method, url, body, contentType) => {
    return fetch(url, {
        credentials: 'include',
        method: method,
        headers: {
          'Content-Type': contentType,
          'X-XSRF-TOKEN': API.XSRF_TOKEN
        },
        body: JSON.stringify(body)
      })
}

const createPost = (url, body, contentType) => createRequest('POST', url, body, contentType);

const rejectEnvelope = (reason) => createPost(API.REJECT_URL, reason, Content.JSON);

const redirect = (url) => window.location.href = url;

const redirRejected = () => redirect(API.REJECT_REDIR_URL);