DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`ticket_setPreviousState`(vTicketFk INT)
BEGIN
	DECLARE vControlFk INT;

	SELECT MAX(id) INTO vControlFk
		FROM ticketTracking
		WHERE ticketFk = vTicketFk;

	IF (SELECT s.code
			FROM vn.state s
				JOIN ticketTracking tt ON tt.stateFk = s.id
			WHERE tt.id = vControlFk)
		= 'PREVIOUS_PREPARATION' THEN
		SELECT id
				INTO vControlFk
			FROM ticketTracking tt
				JOIN vn.state s ON tt.stateFk = s.id
			WHERE ticketFk = vTicketFk
				AND id < vControlFk
				AND s.code != 'PREVIOUS_PREPARATION'
			ORDER BY id DESC
			LIMIT 1;

		INSERT INTO ticketTracking(stateFk, ticketFk, userFk)
			SELECT s.nextStateFk, tt.ticketFk, account.myUser_getId()
				FROM ticketTracking tt
					JOIN vn.state s ON tt.stateFk = s.id
				WHERE id = vControlFk;
	END IF;
END$$
DELIMITER ;
