DROP TRIGGER IF EXISTS `vncontrol`.`ticketTracking_afterInsert`;

DELIMITER $$
CREATE DEFINER=`root`@`%` TRIGGER `vncontrol`.`ticketTracking_afterInsert`
	AFTER INSERT ON `inter`
	FOR EACH ROW
BEGIN
	REPLACE vn.ticketLastState(ticketFk, ticketTrackingFk, name)
		SELECT NEW.Id_Ticket, NEW.inter_id, `name`
			FROM vn.state
			WHERE id = NEW.state_id;
END$$
DELIMITER ;


DROP TRIGGER IF EXISTS `vncontrol`.`ticketTracking_afterUpdate`;

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

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

DROP TRIGGER IF EXISTS `vncontrol`.`ticketTracking_afterDelete`;

DELIMITER $$
CREATE DEFINER=`root`@`%` TRIGGER `vncontrol`.`ticketTracking_afterDelete`
	AFTER DELETE ON `inter`
	FOR EACH ROW
BEGIN
	DECLARE vTicketFk INT;
	DECLARE vTicketTrackingFk INT;
	DECLARE vStateName VARCHAR(15);

	DECLARE CONTINUE HANDLER FOR SQLSTATE '23000'
	BEGIN
		DELETE FROM vn.ticketLastState
			WHERE ticketFk = OLD.Id_Ticket;
	END;

		SELECT i.Id_Ticket, i.inter_id, s.`name`
			INTO vTicketFk, vTicketTrackingFk, vStateName 
			FROM vncontrol.inter i 
				JOIN vn.state s ON i.state_id = s.id 
			WHERE Id_Ticket = OLD.Id_Ticket 
			ORDER BY odbc_date DESC 
			LIMIT 1;

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