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

module.exports = function(Self) {
    require('../methods/expedition-state/filter')(Self);
    require('../methods/expedition-state/addExpeditionState')(Self);

    Self.observe('before save', async ctx => {
        const models = Self.app.models;
        const changes = ctx.data || ctx.instance;
        const instance = ctx.currentInstance;
        const loopBackContext = LoopBackContext.getCurrentContext();
        const httpCtx = {req: loopBackContext.active};
        const httpRequest = httpCtx.req.http.req;
        const $t = httpRequest.__;
        const myOptions = {};

        if (ctx.options && ctx.options.transaction)
            myOptions.transaction = ctx.options.transaction;

        const newStateType = changes?.typeFk;
        if (newStateType == null) return;

        const expeditionId = changes?.expeditionFk || instance?.expeditionFk;

        const {code} = await models.ExpeditionStateType.findById(
            newStateType,
            {
                fields: ['code']
            },
            myOptions);

        if (code !== 'LOST') return;

        const dataExpedition = await models.Expedition.findById(
            expeditionId, {
                fields: ['ticketFk'],
                include: [{
                    relation: 'ticket',
                    scope: {
                        fields: ['clientFk'],
                        include: [{
                            relation: 'client',
                            scope: {
                                fields: ['name', 'salesPersonFk']
                            }
                        }]
                    }
                }],

            }, myOptions);

        const salesPersonFk = dataExpedition.ticket()?.client()?.salesPersonFk;

        if (salesPersonFk) {
            const url = await Self.app.models.Url.getUrl();
            const fullUrl = `${url}ticket/${dataExpedition.ticketFk}/expedition`;
            const message = $t('ticketLostExpedition', {
                ticketId: dataExpedition.ticketFk,
                expeditionId: expeditionId,
                url: fullUrl
            });
            await models.Chat.sendCheckingPresence(httpCtx, salesPersonFk, message);
        }
    });
};