
USE fetchmetrics;

DROP TRIGGER IF EXISTS fetchmetrics.before_insert_DOG_Assessment_Response;
DROP TRIGGER IF EXISTS fetchmetrics.before_update_DOG_Assessment_Response;

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

DELIMITER //
CREATE TRIGGER fetchmetrics.before_update_DOG_Assessment_Response
BEFORE UPDATE ON fetchmetrics.DOG_Assessment_Response
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_Assessment_Response_Audit (
		  id_response
        , name_field
        , value_prev
        , value_new
        , id_change_set
    )
	-- Changed id_assessment_command_modality_link
	SELECT NEW.id_response, 'id_assessment_command_modality_link', CONVERT(OLD.id_assessment_command_modality_link, CHAR), CONVERT(NEW.id_assessment_command_modality_link, CHAR), NEW.id_change_set
		WHERE NOT (OLD.id_assessment_command_modality_link <=> NEW.id_assessment_command_modality_link)
	UNION
	-- Changed id_response_quality_metric
	SELECT NEW.id_response, 'id_response_quality_metric', CONVERT(OLD.id_response_quality_metric, CHAR), CONVERT(NEW.id_response_quality_metric, CHAR), NEW.id_change_set
		WHERE NOT (OLD.id_response_quality_metric <=> NEW.id_response_quality_metric)
	UNION
	-- Changed id_obedience_level
	SELECT NEW.id_response, 'id_obedience_level', CONVERT(OLD.id_obedience_level, CHAR), CONVERT(NEW.id_obedience_level, CHAR), NEW.id_change_set
		WHERE NOT (OLD.id_obedience_level <=> NEW.id_obedience_level)
	UNION
	-- Changed value_measured
	SELECT NEW.id_response, 'value_measured', CONVERT(OLD.value_measured, CHAR), CONVERT(NEW.value_measured, CHAR), NEW.id_change_set
		WHERE NOT (OLD.value_measured <=> NEW.value_measured)
	UNION
	-- Changed notes
	SELECT NEW.id_response, 'notes', OLD.notes, NEW.notes, NEW.id_change_set
		WHERE NOT (OLD.notes <=> NEW.notes)
	UNION
	-- Changed active
	SELECT NEW.id_response, '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 ;
