DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `stock`.`inbound_sync`(vSelf INT)
BEGIN
/**
 * Associates a inbound with their possible outbounds, updating it's available.
 *
 * @param vSelf The inbound identifier
 */
	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 vOutboundFk INT;
	DECLARE vLack INT;
	DECLARE vHasPicks BOOL;
	DECLARE vDone BOOL;

	DECLARE vOutbounds CURSOR FOR
		SELECT id, lack, lack < quantity
			FROM outbound
			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 inbound
		WHERE id = vSelf;

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

	OPEN vOutbounds;

	myLoop: LOOP
		SET vDone = FALSE;
		FETCH vOutbounds INTO vOutboundFk, vLack, vHasPicks;

		IF vDone THEN
			LEAVE myLoop;
		END IF;

		SET vSupplied = LEAST(vAvailable, vLack);

		IF vSupplied > 0 THEN
			SET vAvailable = vAvailable - vSupplied;
			UPDATE outbound
				SET lack = lack - vSupplied
				WHERE id = vOutboundFk;
		END IF;

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

		IF vSupplied > 0 THEN
			CALL inbound_addPick(vSelf, vOutboundFk, vSupplied);
		END IF;

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

	CLOSE vOutbounds;

	UPDATE inbound
		SET isSync = TRUE,
			available = vAvailable
		WHERE id = vSelf;
END$$
DELIMITER ;
