import { getCookie } from "./cookie.js"

let form = document.querySelector('.order-create-form')

// Render the PayPal button into #paypal-button-container
paypal.Buttons({

    style: {
        color: "gold",
        shape: "rect",
        layout: "vertical"
    },

    // Call your server to set up the transaction
    createOrder: function(data, actions) {
        const formData = new FormData(form)

        // get the csrftoken
        const csrftoken = getCookie("csrftoken")

        const options = {
            method: "POST",
            body: new URLSearchParams(formData),
            mode: "same-origin",
        };

        // construct a new Request passing in the csrftoken
        const request = new Request('/checkout/', {
            headers: { "X-CSRFToken": csrftoken },
        })

        return fetch(request, options)
            .then((response) => response.json())
            .then((order) => order.id)
    },

    // Call your server to finalize the transaction
    onApprove: (data, actions) => {
        const csrftoken = getCookie("csrftoken")
        return fetch('/paypal/order/' + data.orderID + '/capture/', {
            method: 'post',
            headers: {'X-CSRFToken': csrftoken}
        })
        .then((response) => response.json())
        .then((orderData) => {
            var errorDetail = Array.isArray(orderData.details) && orderData.details[0];

            if (errorDetail && errorDetail.issue === 'INSTRUMENT_DECLINED') {
                return actions.restart(); // Recoverable state, per:
                // https://developer.paypal.com/docs/checkout/integration-features/funding-failure/
            }

            if (errorDetail) {
                var msg = 'Sorry, your transaction could not be processed.';
                if (errorDetail.description) msg += '\n\n' + errorDetail.description;
                if (orderData.debug_id) msg += ' (' + orderData.debug_id + ')';
                // Show a failure message
                return actions.redirect(orderData.redirect_urls['cancel_url'])
            }

            // Successful capture!
            actions.redirect(orderData.redirect_urls['return_url'])
        });
    }
}).render('#paypal-button-container');
