'use strict';

var server = require('server');
server.extend(module.superModule);

var csrfProtection = require('*/cartridge/scripts/middleware/csrf');
var userLoggedIn = require('*/cartridge/scripts/middleware/userLoggedIn');
var consentTracking = require('*/cartridge/scripts/middleware/consentTracking');
var paymentMiddleware = require('*/cartridge/scripts/middleware/paymentInstruments/payment');

server.prepend(
    'AddPayment',
    csrfProtection.generateToken,
    consentTracking.consent,
    userLoggedIn.validateLoggedIn,
    function (req, res, next) {
        var URLUtils = require('dw/web/URLUtils');
        // Remove addPaymentUrl because Redsys only save payment instruments after order finish successfully
        res.redirect(URLUtils.url('Account-Show'));
        return next();
    });

server.append(
    'List',
    userLoggedIn.validateLoggedIn,
    consentTracking.consent,
    function (req, res, next) {
        var viewData = res.getViewData();
        // Remove addPaymentUrl because Redsys only save payment instruments after order finish successfully
        viewData.addPaymentUrl = null;
        return next();
    });

server.prepend(
    'SavePayment',
    csrfProtection.validateAjaxRequest,
    function (req, res, next) {
        var URLUtils = require('dw/web/URLUtils');
        // Remove addPaymentUrl because Redsys only save payment instruments after order finish successfully
        res.redirect(URLUtils.url('Account-Show'));
        return next();
    });

server.append('DeletePayment', userLoggedIn.validateLoggedInAjax, paymentMiddleware.deletePayment);

module.exports = server.exports();
