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

module.exports = Self => {
    Self.observe('before save', async ctx => {
        const models = Self.app.models;
        const changes = ctx.currentInstance || ctx.instance;

        if (changes && !ctx.isNewInstance) {
            const ticketId = changes.ticketFk;
            const isLocked = await models.Ticket.isLocked(ticketId);
            if (isLocked)
                throw new UserError(`The current ticket can't be modified`);
        }

        if (changes && changes.ticketServiceTypeFk) {
            const ticketServiceType = await models.TicketServiceType.findById(changes.ticketServiceTypeFk);
            changes.description = ticketServiceType.name;
        }
    });

    Self.observe('before delete', async ctx => {
        const models = Self.app.models;
        const service = await models.TicketService.findById(ctx.where.id);
        const isLocked = await models.Ticket.isLocked(service.ticketFk);

        if (isLocked)
            throw new UserError(`The current ticket can't be modified`);
    });
};