DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`business_beforeUpdate`
	BEFORE UPDATE ON `business`
	FOR EACH ROW
BEGIN
	DECLARE isOverlapping BOOL;

	SET NEW.editorFk = account.myUser_getId();
	
	IF NEW.ended IS NULL THEN
		SET NEW.payedHolidays = 0;
	END IF;

	IF !(OLD.started <=> NEW.started AND OLD.ended <=> NEW.ended) THEN
		SELECT util.hasDateOverlapped(
					started,
					ended,
					NEW.started, 
					IFNULL(NEW.ended, b.started)
				) isOverlapped INTO isOverlapping
			FROM vn.business b
			WHERE workerFk = NEW.workerFK
				AND b.id <> NEW.id
			ORDER BY isOverlapped DESC 
			LIMIT 1;
			
		IF isOverlapping THEN 
			CALL util.throw ('IS_OVERLAPPING');
		END IF;
	END IF;
END$$
DELIMITER ;
