DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_setNextState`(
	vSelf INT
)
BEGIN
/**
 * Cambia el estado del ticket al siguiente estado según la tabla state.
 *
 * @param vSelf Id ticket
 */
	DECLARE vStateFk INT;
	DECLARE vNewStateFk INT;

	DECLARE EXIT HANDLER FOR SQLEXCEPTION
	BEGIN
		RESIGNAL;
	END;

	SELECT stateFk INTO vStateFk
		FROM ticketState
		WHERE ticketFk = vSelf;

	SELECT nextStateFk INTO vNewStateFk
		FROM state
		WHERE id = vStateFk;

	IF vNewStateFk IS NULL THEN
		CALL util.throw('The ticket not have next state');
	END IF;

	INSERT INTO ticketTracking(stateFk, ticketFk, userFk)
		VALUES (vNewStateFk, vSelf, account.myUser_getId());
END$$
DELIMITER ;
