'use strict';

var collections = require('*/cartridge/scripts/util/collections');
var Transaction = require('dw/system/Transaction');
var RedsysConstants = require('*/cartridge/scripts/constants/redsysConstants');
var Logger = require('dw/system/Logger');
var logger = Logger.getLogger('Redsys', 'bizum');

/**
 * Verifies that entered Redsys Bizum information is valid. If the information is valid a
 * Redsys Bizum payment instrument is created
 * @param {dw.order.Basket} basket Current users's basket
 * @return {Object} returns an error object
 */
function Handle(basket) {
    var currentBasket = basket;
    var amount = basket.totalGrossPrice;

    try {
        Transaction.wrap(function () {
            var paymentInstruments = currentBasket.getPaymentInstruments();

            collections.forEach(paymentInstruments, function (item) {
                currentBasket.removePaymentInstrument(item);
            });

            currentBasket.createPaymentInstrument(
                RedsysConstants.REDSYS_BIZUM, amount
            );
        });
    } catch (e) {
        logger.error('Error creating payment instrument: {0}', RedsysConstants.REDSYS_BIZUM);
    }

    return { fieldErrors: {}, serverErrors: [], error: false };
}

/**
 * Authorizes a payment using Redsys Bizum.
 * @param {number} orderNumber - The current order's number
 * @param {dw.order.Order} order - Customers's order
 * @param {dw.order.PaymentInstrument} paymentInstrument -  The payment instrument to authorize
 * @param {dw.order.PaymentProcessor} paymentProcessor -  The payment processor of the current
 *      payment method
 * @return {Object} returns an error object
 */
function Authorize(orderNumber, order, paymentInstrument, paymentProcessor) {
    var Resource = require('dw/web/Resource');
    var serverErrors = [];
    var fieldErrors = {};
    var error = false;

    try {
        Transaction.wrap(function () {
            paymentInstrument.paymentTransaction.setTransactionID(orderNumber);
            paymentInstrument.paymentTransaction.setPaymentProcessor(paymentProcessor);
        });
    } catch (e) {
        logger.error('Error authorising payment in order: {0} with error: {1}', orderNumber, e);
        error = true;
        serverErrors.push(
            Resource.msg('error.technical', 'checkout', null)
        );
    }

    return { fieldErrors: fieldErrors, serverErrors: serverErrors, error: error };
}

exports.Handle = Handle;
exports.Authorize = Authorize;
