DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `hedera`.`tpvTransaction_confirmFromExport`()
BEGIN
/**
 * Confirms multiple transactions comming from Redsys "canales" exported CSV.
 *
 * @table tmp.transactions(id, isAuthorization, amount) The list of exported transactions
 */
	DECLARE vDone BOOL;
	DECLARE vTransactionId INT;
	DECLARE vAmount INT;
	DECLARE vConfirmedAmount INT;

	DECLARE cur CURSOR FOR
		SELECT * FROM tPendingTransactions;

	DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;

	CREATE OR REPLACE TEMPORARY TABLE tPendingTransactions
		ENGINE = MEMORY
		SELECT t.id, t.amount, tt.amount confirmedAmount
			FROM tmp.transactions t
				JOIN hedera.tpvTransaction tt ON tt.id = t.id
			WHERE t.isAuthorization
				AND tt.response IS NULL;

	OPEN cur;

	l: LOOP
		SET vDone = FALSE;
		FETCH cur INTO vTransactionId, vAmount, vConfirmedAmount;

		IF vDone THEN
			LEAVE l;
		END IF;

		IF NOT (vAmount <=> vConfirmedAmount) THEN
			CALL util.throw(CONCAT(
				'Transaction ', vTransactionId ,', source  amount "', vAmount ,
				'" does not match confirmed amount "', vConfirmedAmount ,'"'
			));
		END IF;

		CALL tpvTransaction_confirmById(vTransactionId);
	END LOOP;

	CLOSE cur;

	SELECT id, amount FROM tPendingTransactions;

	DROP TEMPORARY TABLE tPendingTransactions;
END$$
DELIMITER ;
