const validateIban = require('vn-loopback/util/validateIban');
const LoopBackContext = require('loopback-context');

module.exports = Self => {
    Self.validateAsync('iban', ibanValidation, {
        message: 'The IBAN does not have the correct format'
    });

    async function ibanValidation(err, done) {
        if (!this.bankEntityFk)
            return done();

        const bankEntity = await Self.app.models.BankEntity.findById(this.bankEntityFk);
        const filter = {
            fields: ['code'],
            where: {id: bankEntity?.countryFk}
        };

        const country = await Self.app.models.Country.findOne(filter);

        if (!validateIban(this.iban, country?.code))
            err();
        done();
    }
    Self.observe('after save', async ctx => {
        const loopBackContext = LoopBackContext.getCurrentContext();
        const models = Self.app.models;
        const user = await models.VnUser.findById(loopBackContext.active.accessToken.userId);
        const bankEntity = await models.BankEntity.findById(ctx.instance.bankEntityFk);
        await Self.app.models.Mail.create({
            receiver: 'finanzas@verdnatura.es',
            subject: 'Añadida cuenta bancaria al proveedor' + ctx.instance.supplierFk,
            body: user.username + ' ha añadido: ' +
                ctx.instance.iban + ', entidad: ' + bankEntity.name + ', bic: ' + bankEntity.bic
        });
    });

    Self.observe('after save', async ctx => {
        const options = {};

        if (ctx.options && ctx.options.transaction)
            options.transaction = ctx.options.transaction;
        const supplier = await Self.app.models.Supplier.findById(ctx.instance.supplierFk, null, options);

        if (supplier.isPayMethodChecked)
            await supplier.updateAttribute('isPayMethodChecked', false, options);
    });
};