let UserError = require('vn-loopback/util/user-error');
let getFinalState = require('vn-loopback/util/hook').getFinalState;
let isMultiple = require('vn-loopback/util/hook').isMultiple;

module.exports = Self => {
    require('../methods/address/getAddress')(Self);

    Self.validateAsync('isEqualizated', cannotHaveET, {
        message: 'Cannot check Equalization Tax in this NIF/CIF'
    });

    async function cannotHaveET(err, done) {
        let client = await Self.app.models.Client.findById(this.clientFk);
        let cannotHaveET;
        if (client && client.fi) {
            let tin = client.fi.toUpperCase();
            cannotHaveET = /^[A-B]/.test(tin);
        } else
            cannotHaveET = false;

        if (cannotHaveET && this.isEqualizated)
            err();
        done();
    }

    Self.validateAsync('postalCode', hasValidPostcode, {
        message: `The postcode doesn't exist. Please enter a correct one`
    });

    async function hasValidPostcode(err, done) {
        if (!this.postalCode)
            return done();

        const models = Self.app.models;
        const postcode = await models.Postcode.findById(this.postalCode);

        if (!postcode) err();
        done();
    }

    Self.beforeRemote('findById', function(ctx, modelInstance, next) {
        ctx.args.filter = {
            include: [{
                relation: 'province',
                scope: {
                    fields: ['id', 'name']
                }
            }, {
                relation: 'agencyMode',
                scope: {
                    fields: ['id', 'name']
                }
            }]
        };
        next();
    });

    // Helpers

    Self.observe('before save', async function(ctx) {
        const Client = Self.app.models.Client;

        if (isMultiple(ctx)) return;

        let transaction = {};
        if (ctx.options && ctx.options.transaction)
            transaction = ctx.options.transaction;

        let changes = ctx.data || ctx.instance;
        let finalState = getFinalState(ctx);

        const client = await Client.findById(finalState.clientFk, {
            fields: ['isEqualizated', 'defaultAddressFk']
        }, {transaction});

        if (changes.isActive == false && client.defaultAddressFk === finalState.id)
            throw new UserError('The default consignee can not be unchecked');

        // Propagate client isEqualizated to all addresses
        if (ctx.isNewInstance == true)
            ctx.instance.isEqualizated = client.isEqualizated;
    });
};