const axios = require('axios');
const {DOMParser} = require('xmldom');

module.exports = Self => {
    Self.remoteMethod('internationalExpedition', {
        description: 'Create an expedition and return a label',
        accessType: 'WRITE',
        accepts: [{
            arg: 'expeditionFk',
            type: 'number',
            required: true
        }],
        returns: {
            type: ['object'],
            root: true
        },
        http: {
            path: `/internationalExpedition`,
            verb: 'POST'
        }
    });

    Self.internationalExpedition = async (expeditionFk) => {
        const models = Self.app.models;

        const viaexpressConfig = await models.ViaexpressConfig.findOne({
            fields: ['url']
        });

        const renderedXml = await models.ViaexpressConfig.renderer(expeditionFk);
        const response = await axios.post(`${viaexpressConfig.url}ServicioVxClientes.asmx`, renderedXml, {
            headers: {
                'Content-Type': 'application/soap+xml; charset=utf-8'
            }
        });

        const xmlString = response.data;
        const parser = new DOMParser();
        const xmlDoc = parser.parseFromString(xmlString, 'text/xml');
        const referenciaVxElement = xmlDoc.getElementsByTagName('ReferenciaVx')[0];
        const referenciaVx = referenciaVxElement.textContent;

        return referenciaVx;
    };
};