
USE fetchmetrics;

DROP TRIGGER IF EXISTS fetchmetrics.before_insert_DOG_Dog_User_Link;
DROP TRIGGER IF EXISTS fetchmetrics.before_update_DOG_Dog_User_Link;

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

DELIMITER //
CREATE TRIGGER fetchmetrics.before_update_DOG_Dog_User_Link
BEFORE UPDATE ON fetchmetrics.DOG_Dog_User_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 fetchmetrics.DOG_Dog_User_Link_Audit (
		  id_link
        , name_field
        , value_prev
        , value_new
        , id_change_set
    )
    -- Changed dog
	SELECT NEW.id_link, 'id_dog', CONVERT(OLD.id_dog, CHAR), CONVERT(NEW.id_dog, CHAR), NEW.id_change_set
		WHERE NOT OLD.id_dog <=> NEW.id_dog
	UNION
    -- Changed 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 access_level
	SELECT NEW.id_link, 'id_access_level', CONVERT(OLD.id_access_level, CHAR), CONVERT(NEW.id_access_level, CHAR), NEW.id_change_set
		WHERE NOT OLD.id_access_level <=> NEW.id_access_level
    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 ;
