DROP TRIGGER IF EXISTS `vn2008`.`TicketsAfterUpdate`;

DELIMITER $$
USE `vn2008`$$
CREATE DEFINER=`root`@`%` TRIGGER `vn2008`.`TicketsAfterUpdate`
	AFTER UPDATE ON `Tickets` FOR EACH ROW
BEGIN
	IF NEW.Id_Ruta IS NULL AND OLD.Id_Ruta IS NOT NULL THEN
		INSERT INTO vn.routeLog(originFk, userFk, `action`, description)
			VALUES (OLD.Id_Ruta, account.userGetId(), 'update', CONCAT('Saca el ticket ', OLD.Id_Ticket, ' de la ruta'));
    ELSEIF NOT (NEW.Id_Ruta <=> OLD.Id_Ruta) THEN
		INSERT INTO vn.routeLog(originFk, userFk, `action`, description)
			VALUES (NEW.Id_Ruta, account.userGetId(), 'update', CONCAT('Añade el ticket ', OLD.Id_Ticket, ' a la ruta'));
    END IF;
    
	CALL stock.queueAdd ('ticket', NEW.Id_Ticket, OLD.Id_Ticket);
    
    INSERT INTO vn.localLog(ticketFk)
		VALUES(NEW.Id_Ticket);
END$$
DELIMITER ;
