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

let form = document.querySelector('form.order__form')

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

    // 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(function(res) {
            return res.json();
        }).then(function(orderData) {
            return orderData.id;
        });
    },

    // Call your server to finalize the transaction
    onApprove: function(data, actions) {
        const csrftoken = getCookie("csrftoken")
        return fetch('/paypal/order/' + data.orderID + '/capture/', {
            method: 'post',
            headers: {'X-CSRFToken': csrftoken}
        }).then(function(res) {
            return res.json();
        }).then(function(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');



// RETURNED DATA
// {
//   "id": "1WM83684A69628456",
//   "status": "COMPLETED",
//   "purchase_units": [
//     {
//       "reference_id": "default",
//       "shipping": {
//         "name": {
//           "full_name": "John Doe"
//         },
//         "address": {
//           "address_line_1": "1 Main St",
//           "admin_area_2": "San Jose",
//           "admin_area_1": "CA",
//           "postal_code": "95131",
//           "country_code": "US"
//         }
//       },
//       "payments": {
//         "captures": [
//           {
//             "id": "9AU23265T5630860D",
//             "status": "COMPLETED",
//             "amount": {
//               "currency_code": "USD",
//               "value": "13.40"
//             },
//             "final_capture": true,
//             "seller_protection": {
//               "status": "ELIGIBLE",
//               "dispute_categories": [
//                 "ITEM_NOT_RECEIVED",
//                 "UNAUTHORIZED_TRANSACTION"
//               ]
//             },
//             "seller_receivable_breakdown": {
//               "gross_amount": {
//                 "currency_code": "USD",
//                 "value": "13.40"
//               },
//               "paypal_fee": {
//                 "currency_code": "USD",
//                 "value": "0.96"
//               },
//               "net_amount": {
//                 "currency_code": "USD",
//                 "value": "12.44"
//               }
//             },
//             "links": [
//               {
//                 "href": "https://api.sandbox.paypal.com/v2/payments/captures/9AU23265T5630860D",
//                 "rel": "self",
//                 "method": "GET"
//               },
//               {
//                 "href": "https://api.sandbox.paypal.com/v2/payments/captures/9AU23265T5630860D/refund",
//                 "rel": "refund",
//                 "method": "POST"
//               },
//               {
//                 "href": "https://api.sandbox.paypal.com/v2/checkout/orders/1WM83684A69628456",
//                 "rel": "up",
//                 "method": "GET"
//               }
//             ],
//             "create_time": "2022-02-28T15:33:07Z",
//             "update_time": "2022-02-28T15:33:07Z"
//           }
//         ]
//       }
//     }
//   ],
//   "payer": {
//     "name": {
//       "given_name": "John",
//       "surname": "Doe"
//     },
//     "email_address": "sb-rlst914027742@personal.example.com",
//     "payer_id": "G9RGHQ72CGKF6",
//     "address": {
//       "country_code": "US"
//     }
//   },
//   "links": [
//     {
//       "href": "https://api.sandbox.paypal.com/v2/checkout/orders/1WM83684A69628456",
//       "rel": "self",
//       "method": "GET"
//     }
//   ]
// }
