DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `hedera`.`tpvTransaction_start`(
	vAmount INT,
	vCompany INT,
	vUser INT)
BEGIN
/**
 * Start a new transaction with the virtual TPV, generating an identifier
 * of transaction and returning the parameters that should be sent to the
 * payment platform.
 *
 * @param vAmount Amount to pay in cents
 * @param vCompany The company identifier
 * @select Parameters that will be sent to payment platform
 */
	DECLARE vSelf CHAR(12);
	DECLARE vMerchant INT;
	DECLARE vUrl VARCHAR(255);
	DECLARE vKey VARCHAR(50);
	DECLARE vEnvironment VARCHAR(255);

	DECLARE EXIT HANDLER FOR SQLEXCEPTION
	BEGIN
		ROLLBACK;
		RESIGNAL;
	END;

	START TRANSACTION;

	IF vCompany IS NULL THEN
		SELECT companyFk INTO vCompany
			FROM tpvMerchantEnable LIMIT 1;
	END IF;

	SELECT merchantFk INTO vMerchant
		FROM tpvMerchantEnable WHERE companyFk = vCompany;

	SELECT environment INTO vEnvironment
		FROM util.config;

	IF vEnvironment = 'production' THEN
		SELECT c.url, m.secretKey INTO vUrl, vKey
			FROM tpvMerchant m
			JOIN tpvConfig c
				WHERE m.id = vMerchant;
	ELSE
		SELECT testUrl, testKey INTO vUrl, vKey
			FROM tpvConfig;
	END IF;

	INSERT INTO tpvTransaction
		SET merchantFk = vMerchant,
			clientFk = vUser,
			amount = vAmount;

	SET vSelf = LAST_INSERT_ID();

	SELECT vAmount amount,
			vSelf transactionId,
			vMerchant merchant,
			currency,
			transactionType,
			terminal,
			merchantUrl,
			vUrl url,
			vKey secretKey
		FROM tpvConfig;

	COMMIT;
END$$
DELIMITER ;
