DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `stock`.`buyLot_sync`(vSelf INT)
BEGIN
/**
 * Associates a lot with their possible buyOuts, updating it's available.
 *
 * @param vSelf The lot id
 */
	DECLARE vDated DATETIME;
	DECLARE vExpired DATETIME;
	DECLARE vItem INT;
	DECLARE vWarehouse INT;
	DECLARE vQuantity INT;
	DECLARE vAvailable INT;
	DECLARE vSupplied INT;
	DECLARE vSuppliedFromRequest INT;
	DECLARE vOutFk INT;
	DECLARE vLack INT;
	DECLARE vHasPicks BOOL;
	DECLARE vDone BOOL;

	DECLARE vOuts CURSOR FOR
		SELECT outFk, lack, lack < quantity
			FROM buyOut
			WHERE warehouseFk = vWarehouse
				AND itemFk = vItem
				AND dated >= vDated
				AND (vExpired IS NULL OR dated < vExpired)
			ORDER BY dated, created;

	DECLARE CONTINUE HANDLER FOR NOT FOUND
		SET vDone = TRUE;

	SELECT warehouseFk, itemFk, available, quantity, expired, dated
		INTO vWarehouse, vItem, vAvailable, vQuantity, vExpired, vDated
		FROM buyLot
		WHERE buyFk = vSelf;

	IF vAvailable IS NULL THEN
		SET vAvailable = vQuantity;
	END IF;

	OPEN vOuts;

	myLoop: LOOP
		SET vDone = FALSE;
		FETCH vOuts INTO vOutFk, vLack, vHasPicks;

		IF vDone THEN
			LEAVE myLoop;
		END IF;

		SET vSupplied = LEAST(vAvailable, vLack);

		IF vSupplied > 0 THEN
			SET vAvailable = vAvailable - vSupplied;
			UPDATE buyOut
				SET lack = lack - vSupplied
				WHERE outFk = vOutFk;
		END IF;

		IF vHasPicks AND vAvailable > 0 THEN
			CALL buyOut_requestQuantity(vOutFk, vAvailable, vDated, vSuppliedFromRequest);
			SET vSupplied = vSupplied + vSuppliedFromRequest;
			SET vAvailable = vAvailable - vSuppliedFromRequest;
		END IF;

		IF vSupplied > 0 THEN
			CALL buyLot_addPick(vSelf, vOutFk, vSupplied);
		END IF;

		IF vAvailable <= 0 THEN
			LEAVE myLoop;
		END IF;
	END LOOP;

	CLOSE vOuts;

	UPDATE buyLot
		SET isSync = TRUE,
			available = vAvailable
		WHERE buyFk = vSelf;
END$$
DELIMITER ;
