const UserError = require('vn-loopback/util/user-error');
const LoopBackContext = require('loopback-context');

module.exports = Self => {
    Self.validatesPresenceOf('typeFk', {
        message: 'Sample type cannot be blank'
    });

    Self.observe('before save', async function(ctx) {
        const models = Self.app.models;
        const changes = ctx.data || ctx.instance;

        const sample = await models.Sample.findById(changes.typeFk);

        if (sample.hasCompany && !changes.companyFk)
            throw new UserError('Choose a company');

        const mandateSamples = [
            {sample: 'sepa-core', type: 'CORE'},
            {sample: 'client-lcr', type: 'LCR'}
        ];

        const mandate = mandateSamples.find(mandate => {
            return mandate.sample === sample.code;
        });

        // Renew mandate
        if (mandate) {
            const mandateType = await models.MandateType.findOne({
                where: {name: mandate.type}
            });

            const oldMandate = await models.Mandate.findOne({
                where: {
                    clientFk: changes.clientFk,
                    companyFk: changes.companyFk,
                    mandateTypeFk: mandateType.id,
                    finished: null
                }
            });

            // Disable old mandate
            if (oldMandate)
                oldMandate.updateAttribute('finished', Date.vnNew());

            // Create a new mandate
            await models.Mandate.create({
                clientFk: changes.clientFk,
                companyFk: changes.companyFk,
                mandateTypeFk: mandateType.id
            });
        }

        const loopBackContext = LoopBackContext.getCurrentContext();

        changes.userFk = loopBackContext.active.accessToken.userId;
    });
};