DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`ticketTracking_afterUpdate`
	AFTER UPDATE ON `ticketTracking`
	FOR EACH ROW
BEGIN
	DECLARE vTicketFk INT;
    DECLARE vTicketTrackingFk INT;
    DECLARE vStateName VARCHAR(15);
    
	IF NEW.stateFk <> OLD.stateFk THEN
		REPLACE vn.ticketLastState(ticketFk, ticketTrackingFk, name)
			SELECT NEW.ticketFk, NEW.id, `name`
				FROM state
				WHERE id = NEW.stateFk;
    END IF;
    
    IF NEW.ticketFk <> OLD.ticketFk THEN
		SELECT i.ticketFk, i.id, s.`name`
			INTO vTicketFk, vTicketTrackingFk, vStateName 
			FROM ticketTracking i 
				JOIN state s ON i.stateFk = s.id 
			WHERE ticketFk = NEW.ticketFk 
			ORDER BY created DESC 
			LIMIT 1;

		IF vTicketFk > 0 THEN
			REPLACE INTO ticketLastState(ticketFk, ticketTrackingFk,name)
				VALUES(vTicketFk, vTicketTrackingFk, vStateName);
		END IF;
	END IF;
END$$
DELIMITER ;
