
USE parts;

DROP TRIGGER IF EXISTS parts.before_insert_DOG_Assessment;
DROP TRIGGER IF EXISTS parts.before_update_DOG_Assessment;

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

DELIMITER //
CREATE TRIGGER parts.before_update_DOG_Assessment
BEFORE UPDATE ON parts.DOG_Assessment
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 parts.DOG_Assessment_Audit (
		  id_assessment
        , name_field
        , value_prev
        , value_new
        , id_change_set
    )
	-- Changed id_weather
	SELECT NEW.id_assessment, 'id_weather', CONVERT(OLD.id_weather, CHAR), CONVERT(NEW.id_weather, CHAR), NEW.id_change_set
		WHERE NOT (OLD.id_weather <=> NEW.id_weather)
	UNION
	-- Changed id_lighting_level
	SELECT NEW.id_assessment, 'id_lighting_level', CONVERT(OLD.id_lighting_level, CHAR), CONVERT(NEW.id_lighting_level, CHAR), NEW.id_change_set
		WHERE NOT (OLD.id_lighting_level <=> NEW.id_lighting_level)
	UNION
	-- Changed id_location
	SELECT NEW.id_assessment, 'id_location', CONVERT(OLD.id_location, CHAR), CONVERT(NEW.id_location, CHAR), NEW.id_change_set
		WHERE NOT (OLD.id_location <=> NEW.id_location)
	UNION
	-- Changed id_user_handler
	SELECT NEW.id_assessment, 'id_user_handler', CONVERT(OLD.id_user_handler, CHAR), CONVERT(NEW.id_user_handler, CHAR), NEW.id_change_set
		WHERE NOT (OLD.id_user_handler <=> NEW.id_user_handler)
	UNION
	-- Changed notes
	SELECT NEW.id_assessment, 'notes', OLD.notes, NEW.notes, NEW.id_change_set
		WHERE NOT (OLD.notes <=> NEW.notes)
	UNION
	-- Changed temperature_celcius
	SELECT NEW.id_assessment, 'temperature_celcius', CONVERT(OLD.temperature_celcius, CHAR), CONVERT(NEW.temperature_celcius, CHAR), NEW.id_change_set
		WHERE NOT (OLD.temperature_celcius <=> NEW.temperature_celcius)
	UNION
	-- Changed active
	SELECT NEW.id_assessment, '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 ;
