DROP TRIGGER IF EXISTS `vn`.`supplier_beforeUpdate`;
USE `vn`;

DELIMITER $$
$$
CREATE DEFINER=`root`@`localhost` TRIGGER `vn`.`supplier_beforeUpdate`
	BEFORE UPDATE ON `supplier`
	FOR EACH ROW
BEGIN
	DECLARE vHasChange BOOL;
	DECLARE vPayMethodChanged BOOL;
	DECLARE vPayMethodHasVerified BOOL;
    DECLARE vParams JSON;
	DECLARE vOldPayMethodName VARCHAR(20);
	DECLARE vNewPayMethodName VARCHAR(20);

	SELECT hasVerified INTO vPayMethodHasVerified
		FROM payMethod
			WHERE id = NEW.payMethodFk;

	SET vPayMethodChanged = NOT(NEW.payMethodFk <=> OLD.payMethodFk);

	IF vPayMethodChanged THEN
		SELECT name INTO vOldPayMethodName
			FROM payMethod
				WHERE id = OLD.payMethodFk;
		SELECT name INTO vNewPayMethodName
			FROM payMethod
				WHERE id = NEW.payMethodFk;

		SET vParams = JSON_OBJECT(
					'name', NEW.name,
					'oldPayMethod', vOldPayMethodName,
					'newPayMethod', vNewPayMethodName
				);
		SELECT util.notification_send('supplier-pay-method-update', vParams, NULL) INTO @id;
	END IF;

	SET vHasChange =  NOT(NEW.payDemFk <=> OLD.payDemFk AND NEW.payDay <=> OLD.payDay) OR vPayMethodChanged;

	IF vHasChange AND vPayMethodHasVerified THEN
		SET NEW.isPayMethodChecked = FALSE;
	END IF;

END$$
DELIMITER ;
