const LoopBackContext = require('loopback-context');

module.exports = function(Self) {
    Self.validateCredit = function(credit) {
        return credit >= 0;
    };

    Self.validateBinded('credit', Self.validateCredit, {
        message: 'The credit must be an integer greater than or equal to zero',
        allowNull: false,
        allowBlank: false
    });

    Self.validateGrade = function(grade) {
        return typeof grade === 'undefined' || grade >= 0;
    };

    Self.validateBinded('grade', Self.validateGrade, {
        message: 'The grade must be an integer greater than or equal to zero',
        allowNull: true
    });

    async function validateNullGrade(err, done) {
        let filter = {
            fields: ['grade'],
            where: {
                creditClassification: this.creditClassification
            },
            order: 'created DESC'
        };
        let insurance = await Self.findOne(filter);

        if (insurance && (!insurance.grade && this.grade || insurance.grade && !this.grade))
            err();

        done();
    }

    Self.validateAsync('nullGrade', validateNullGrade, {
        message: 'The grade must be similar to the last one'
    });

    Self.observe('after save', async function(ctx) {
        const loopBackContext = LoopBackContext.getCurrentContext();
        const httpCtx = {req: loopBackContext.active};
        const options = ctx.options ? ctx.options : null;
        const models = Self.app.models;

        if (!ctx.isNewInstance) return;

        const data = ctx.instance;
        const insurance = await Self.findById(data.id, null, options);
        const client = insurance.classification().customer();
        const salesPerson = client.salesPersonUser();

        if (!salesPerson) return;

        const httpRequest = httpCtx.req.http.req;
        const $t = httpRequest.__;
        const origin = httpRequest.headers.origin;
        const fullPath = `${origin}/#!/client/${client.id}/credit-insurance/index`;
        const message = $t('MESSAGE_INSURANCE_CHANGE', {
            clientId: client.id,
            clientName: client.name,
            credit: data.credit,
            url: fullPath
        });
        await models.Chat.sendCheckingPresence(httpCtx, salesPerson.id, message);
    });
};