
USE fetchmetrics;

DROP TRIGGER IF EXISTS fetchmetrics.before_insert_DOG_Dog;
DROP TRIGGER IF EXISTS fetchmetrics.before_update_DOG_Dog;

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

DELIMITER //
CREATE TRIGGER fetchmetrics.before_update_DOG_Dog
BEFORE UPDATE ON fetchmetrics.DOG_Dog
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_Audit (
		  id_dog
        , name_field
        , value_prev
        , value_new
        , id_change_set
    )
    -- Changed name
	SELECT NEW.id_dog, 'name', OLD.name, NEW.name, NEW.id_change_set
		WHERE NOT OLD.name <=> NEW.name
    UNION
    -- Changed appearance
	SELECT NEW.id_dog, 'appearance', OLD.appearance, NEW.appearance, NEW.id_change_set
		WHERE NOT OLD.appearance <=> NEW.appearance
	UNION
	-- Changed mass_kg
	SELECT NEW.id_dog, 'mass_kg', CONVERT(OLD.mass_kg, CHAR), CONVERT(NEW.mass_kg, CHAR), NEW.id_change_set
		WHERE NOT (OLD.mass_kg <=> NEW.mass_kg)
	UNION
	-- Changed active
	SELECT NEW.id_dog, '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 ;
