
USE partsltd_prod;

DROP TRIGGER IF EXISTS partsltd_prod.before_insert_PH_User_Role_Link;
DROP TRIGGER IF EXISTS partsltd_prod.before_update_PH_User_Role_Link;


DELIMITER //
CREATE TRIGGER partsltd_prod.before_insert_PH_User_Role_Link
BEFORE INSERT ON partsltd_prod.PH_User_Role_Link
FOR EACH ROW
BEGIN
	SET NEW.created_on := IFNULL(NEW.created_on, NOW());
END //
DELIMITER ;


DELIMITER //
CREATE TRIGGER partsltd_prod.before_update_PH_User_Role_Link
BEFORE UPDATE ON partsltd_prod.PH_User_Role_Link
FOR EACH ROW
BEGIN
	IF OLD.id_change_set <=> NEW.id_change_set THEN
		SIGNAL SQLSTATE '45000'
        SET MESSAGE_TEXT = 'New change Set ID must be provided.';
    END IF;
    
    INSERT INTO partsltd_prod.PH_User_Role_Link_Audit (
		id_link,
        name_field,
        value_prev,
        value_new,
        id_change_set
    )
	-- Changed id_user
	SELECT NEW.id_link, 'id_user', CONVERT(OLD.id_user, CHAR), CONVERT(NEW.id_user, CHAR), NEW.id_change_set
		WHERE NOT OLD.id_user <=> NEW.id_user
    UNION
    -- Changed id_role
	SELECT NEW.id_link, 'id_role', CONVERT(OLD.id_role, CHAR), CONVERT(NEW.id_role, CHAR), NEW.id_change_set
		WHERE NOT OLD.id_role <=> NEW.id_role
	UNION
	-- Changed active
	SELECT NEW.id_link, 'active', CONVERT(CONVERT(OLD.active, SIGNED), CHAR), CONVERT(CONVERT(NEW.active, SIGNED), CHAR), NEW.id_change_set
		WHERE NOT (OLD.active <=> NEW.active)
    ;
END //
DELIMITER ;