'use strict';

var Logger = require('dw/system/Logger');
var logger = Logger.getLogger('Redsys', 'redsys');

/**
 * Middleware to handle deleting a payment instrument of REDSYS_CREDIT_CARD.
 * @param {Object} req - Request object
 * @param {Object} res - Response object
 * @param {Function} next - Next call in the middleware chain
 * @returns {void}
 */
function deletePayment(req, res, next) {
    var CustomerMgr = require('dw/customer/CustomerMgr');
    var redsysPaymentCardHelper = require('*/cartridge/scripts/redsys/helpers/redsysPaymentCardHelper');
    var payment = req.querystring.UUID;
    var tokenToDelete = null;

    if (payment) {
        var customer = CustomerMgr.getCustomerByCustomerNumber(req.currentCustomer.profile.customerNo);
        tokenToDelete = redsysPaymentCardHelper.getTokenOfPaymentInstrument(payment, customer);

        if (tokenToDelete) {
            var deletePaymentInstrument = redsysPaymentCardHelper.deletePaymentInstrument(payment, tokenToDelete);
            if (deletePaymentInstrument) {
                return next();
            }
        }
    }

    logger.error('Payment to delete not found');
    this.emit('route:Complete', req, res);
    return null;
}

module.exports = {
    deletePayment: deletePayment
};
