'use strict';

/**
 * RedsysRest
 */

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

var createHttpService = LocalServiceRegistry.createService('int_redsys.http.rest', {
    createRequest: function (svc, params) {
        var BaseURL = svc.getConfiguration().getCredential().getURL();
        try {
            var url = svc.configuration.credential.URL;
            var id = svc.getCredentialID();
            svc.setURL(url);
            svc.setCredentialID(id);
            svc.addHeader('Content-Type', 'application/json');

            if ('action' in params) {
                switch (params.action) {
                    case 'iniciaPeticionREST':
                        svc.setRequestMethod('POST');
                        svc.setURL(BaseURL + '/iniciaPeticionREST');
                        break;

                    case 'trataPeticionREST':
                        svc.setRequestMethod('POST');
                        svc.setURL(BaseURL + '/trataPeticionREST');
                        break;

                    default:
                        throw new Error('unknown `action` parameter value. Value: ' + params.action + '.');
                }
            } else {
                throw new Error('required `action` parameter is empty.');
            }

            return JSON.stringify(params.payload);
        } catch (e) {
            logger.error('Error calling Redsys service', e.message);
        }
        return null;
    },

    parseResponse: function (svc, client) {
        return client.text;
    }
});

module.exports.createHttpService = createHttpService;
