DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn2008`.`compresTriggerBeforeUpdate`(vOldEntrada INT, vNewEntrada INT, oldItem INT, 
	newItem INT, newNoVincular BOOLEAN, newCompra INT)
BEGIN
	DECLARE newWarehouse INTEGER;
    DECLARE hasToRecalculate BOOLEAN;
    
	IF newNoVincular = FALSE THEN
		IF oldItem <> newItem OR vOldEntrada <> vNewEntrada THEN
			SELECT Id_Compra INTO hasToRecalculate FROM travel t
				JOIN Entradas e ON e.travel_id = t.id
				JOIN vn.lastBuy lb ON lb.id = newCompra
			WHERE e.Id_Entrada = vOldEntrada LIMIT 1;
			
			IF hasToRecalculate THEN
				SELECT warehouse_id INTO newWarehouse FROM travel t
					JOIN Entradas e ON t.id = e.travel_id
                    WHERE e.Id_Entrada = vOldEntrada;
				CALL vn.lastBuyRefresh(newWarehouse);
			END IF;
		END IF;
		IF vOldEntrada <> vNewEntrada THEN
			
			UPDATE Entradas oldEntrada
				JOIN travel oldTravel ON oldEntrada.travel_id = oldtravel.id
				JOIN Entradas newEntrada ON newEntrada.Id_Entrada = vNewEntrada
                JOIN travel newTravel ON newTravel.id = newEntrada.travel_id
                JOIN vn.lastBuy lb ON newItem = lb.item AND newTravel.warehouse_id = lb.warehouse
			SET lb.id = newCompra
			WHERE oldEntrada.Id_Entrada = vOldEntrada AND oldTravel.warehouse_id <> newTravel.warehouse_id 
				AND newTravel.landing > lb.landing AND newTravel.landing <= util.VN_CURDATE();
         END IF;
	END IF;
		
END$$
DELIMITER ;
