
USE fetchmetrics;

DROP TRIGGER IF EXISTS fetchmetrics.before_insert_DOG_Image;
DROP TRIGGER IF EXISTS fetchmetrics.before_update_DOG_Image;

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

DELIMITER //
CREATE TRIGGER fetchmetrics.before_update_DOG_Image
BEFORE UPDATE ON fetchmetrics.DOG_Image
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_Image_Audit (
		  id_image
        , name_field
        , value_prev
        , value_new
        , id_change_set
    )
	-- Changed id_file_type
	SELECT NEW.id_image, 'id_file_type', CONVERT(OLD.id_file_type, CHAR), CONVERT(NEW.id_file_type, CHAR), NEW.id_change_set
		WHERE NOT (OLD.id_file_type <=> NEW.id_file_type)
	UNION
	-- Changed id_dog
	SELECT NEW.id_image, '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 path
	SELECT NEW.id_image, 'path', OLD.path, NEW.path, NEW.id_change_set
		WHERE NOT (OLD.path <=> NEW.path)
	UNION
	-- Changed name
	SELECT NEW.id_image, 'name', OLD.name, NEW.name, NEW.id_change_set
		WHERE NOT (OLD.name <=> NEW.name)
	UNION
	-- Changed display_order
	SELECT NEW.id_image, 'display_order', CONVERT(OLD.display_order, CHAR), CONVERT(NEW.display_order, CHAR), NEW.id_change_set
		WHERE NOT (OLD.display_order <=> NEW.display_order)
	UNION
	-- Changed active
	SELECT NEW.id_image, '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 ;
