module.exports = Self => {
    Self.remoteMethod('createWithInsurance', {
        description: 'Creates both classification and one insurance',
        accepts: [{
            arg: 'data',
            type: 'object',
            http: {source: 'body'}
        }, {
            arg: 'context',
            type: 'object',
            http: function(ctx) {
                return ctx;
            }
        }],
        returns: {
            root: true,
            type: 'boolean'
        },
        http: {
            verb: 'post',
            path: '/createWithInsurance'
        }
    });

    Self.createWithInsurance = async(data, ctx) => {
        let tx = await Self.beginTransaction({});

        try {
            let options = {transaction: tx};

            let classificationSchema = {client: data.clientFk, started: data.started};
            let newClassification = await Self.create(classificationSchema, options);
            let CreditInsurance = Self.app.models.CreditInsurance;
            let insuranceSchema = {
                creditClassification: newClassification.id,
                credit: data.credit,
                grade: data.grade
            };

            let newCreditInsurance = await CreditInsurance.create(insuranceSchema, options);
            await tx.commit();
            await CreditInsurance.messageSend(newCreditInsurance, ctx.req.accessToken);

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