DROP PROCEDURE IF EXISTS add_user_in_change_log;;
CREATE PROCEDURE add_user_in_change_log(IN updated_user_id INT(11))
READS SQL DATA
BEGIN
    INSERT INTO users_change_log
        SET user_id = updated_user_id
        ON DUPLICATE KEY UPDATE user_id = updated_user_id;
END;;

DROP PROCEDURE IF EXISTS add_profile_in_change_log;;
CREATE PROCEDURE add_profile_in_change_log(IN updated_profile_id INT(11))
READS SQL DATA
BEGIN
    INSERT INTO users_change_log
        SET user_id = (SELECT user_id FROM users WHERE profile_id = updated_profile_id)
        ON DUPLICATE KEY UPDATE user_id = (SELECT user_id FROM users WHERE profile_id = updated_profile_id);
END;;

DROP TRIGGER IF EXISTS after_users_update;;
CREATE TRIGGER after_users_update
    AFTER UPDATE ON users
    FOR EACH ROW 
BEGIN
    CALL add_user_in_change_log(NEW.user_id);
END;;

DROP TRIGGER IF EXISTS after_users_insert;;
CREATE TRIGGER after_users_insert 
    AFTER INSERT ON users
    FOR EACH ROW 
BEGIN
    CALL add_user_in_change_log(NEW.user_id);
END;;

DROP TRIGGER IF EXISTS after_user_product_option_values_update;;
CREATE TRIGGER after_user_product_option_values_update
    AFTER UPDATE ON user_product_option_values
    FOR EACH ROW 
BEGIN
    CALL add_user_in_change_log(NEW.user_id);
END;;

DROP TRIGGER IF EXISTS after_user_product_option_values_insert;;
CREATE TRIGGER after_user_product_option_values_insert 
    AFTER INSERT ON user_product_option_values
    FOR EACH ROW 
BEGIN
    CALL add_user_in_change_log(NEW.user_id);
END;;

DROP TRIGGER IF EXISTS after_profiles_update;;
CREATE TRIGGER after_profiles_update
    AFTER UPDATE ON profiles
    FOR EACH ROW 
BEGIN
    CALL add_profile_in_change_log(NEW.profile_id);
END;;
