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

module.exports = Self => {
    Self.remoteMethod('deleteExpedition', {
        description: 'Delete a shipment by providing the expedition ID, interacting with Viaexpress API',
        accessType: 'WRITE',
        accepts: [{
            arg: 'expeditionFk',
            type: 'number',
            required: true
        }],
        returns: {
            type: ['object'],
            root: true
        },
        http: {
            path: `/deleteExpedition`,
            verb: 'POST'
        }
    });

    Self.deleteExpedition = async expeditionFk => {
        const models = Self.app.models;

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

        const renderedXml = await models.ViaexpressConfig.deleteExpeditionRenderer(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 resultElement = xmlDoc.getElementsByTagName('DeleteEnvioResult')[0];
        const result = resultElement.textContent;

        return result;
    };
};