module.exports = Self => {
    Self.remoteMethodCtx('updateConcept', {
        description: 'Updates the concept of a sale',
        accessType: 'WRITE',
        accepts: [{
            arg: 'id',
            type: 'number',
            required: true,
            description: 'sale ID',
            http: {source: 'path'}
        }, {
            arg: 'newConcept',
            type: 'any',
            required: true,
            description: 'new concept'
        }],
        returns: {
            type: 'string',
            root: true
        },
        http: {
            path: `/:id/updateConcept`,
            verb: 'post'
        }
    });

    Self.updateConcept = async(ctx, id, newConcept, options) => {
        const models = Self.app.models;
        const myOptions = {};
        let tx;

        if (typeof options == 'object')
            Object.assign(myOptions, options);

        if (!myOptions.transaction) {
            tx = await Self.beginTransaction({});
            myOptions.transaction = tx;
        }

        try {
            const currentLine = await models.Sale.findById(id, null, myOptions);

            await models.Sale.canEdit(ctx, [id], myOptions);

            const line = await currentLine.updateAttributes({concept: newConcept}, myOptions);

            if (tx) await tx.commit();

            return line;
        } catch (e) {
            if (tx) await tx.rollback();
            throw e;
        }
    };
};