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

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

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

        let 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) {
            let mandateType = await models.MandateType.findOne({
                where: {name: mandate.type}
            });

            let 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', new Date());

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

        // Apply workerFk
        let filter = {where: {userFk: ctx.options.accessToken.userId}};
        let worker = await Self.app.models.Worker.findOne(filter);

        changes.workerFk = worker.id;
    });
};