'use strict';

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

var consentTracking = require('*/cartridge/scripts/middleware/consentTracking');

server.prepend(
    'Begin',
    server.middleware.https,
    consentTracking.consent,
    function (req, res, next) {
        var redsysHelper = require('*/cartridge/scripts/redsys/helpers/redsysHelper');
        var viewData = res.getViewData();
        viewData.redsysSFRA5CompatibilityModeEnabled = redsysHelper.redsysSFRA5CompatibilityModeEnabled();

        return next();
    });

server.append(
    'Begin',
    server.middleware.https,
    consentTracking.consent,
    function (req, res, next) {
        var redsysHelper = require('*/cartridge/scripts/redsys/helpers/redsysHelper');
        var redsysPaymentCardHelper = require('*/cartridge/scripts/redsys/helpers/redsysPaymentCardHelper');
        var Resource = require('dw/web/Resource');

        var viewData = res.getViewData();
        viewData.redsysSFRA5CompatibilityModeEnabled = redsysHelper.redsysSFRA5CompatibilityModeEnabled();

        // If the payment fails, it shows an error message received from Redsys
        viewData.error = req.querystring.redsysError;
        if (req.querystring.redsysError) {
            var redsysErrorMessage = Resource.msg('msg.payment.error', 'redsys', null);
            viewData.errorMessage = redsysErrorMessage + redsysPaymentCardHelper.getResponseByCode(req.querystring.redsysError);
        }

        return next();
    });

module.exports = server.exports();
