
USE parts;

DROP TRIGGER IF EXISTS parts.before_insert_DOG_Response_Quality_Metric;
DROP TRIGGER IF EXISTS parts.before_update_DOG_Response_Quality_Metric;

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

DELIMITER //
CREATE TRIGGER parts.before_update_DOG_Response_Quality_Metric
BEFORE UPDATE ON parts.DOG_Response_Quality_Metric
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_Response_Quality_Metric_Audit (
		  id_metric
        , name_field
        , value_prev
        , value_new
        , id_change_set
    )
	-- Changed id_unit_measurement
	SELECT NEW.id_metric, 'id_unit_measurement', CONVERT(OLD.id_unit_measurement, CHAR), CONVERT(NEW.id_unit_measurement, CHAR), NEW.id_change_set
		WHERE NOT (OLD.id_unit_measurement <=> NEW.id_unit_measurement)
	UNION
	-- Changed code
	SELECT NEW.id_metric, 'code', OLD.code, NEW.code, NEW.id_change_set
		WHERE NOT (OLD.code <=> NEW.code)
	UNION
	-- Changed name
	SELECT NEW.id_metric, 'name', OLD.name, NEW.name, NEW.id_change_set
		WHERE NOT (OLD.name <=> NEW.name)
    UNION
	-- Changed value_min
	SELECT NEW.id_metric, 'value_min', CONVERT(OLD.value_min, CHAR), CONVERT(NEW.value_min, CHAR), NEW.id_change_set
		WHERE NOT (OLD.value_min <=> NEW.value_min)
	UNION
	-- Changed value_max
	SELECT NEW.id_metric, 'value_max', CONVERT(OLD.value_max, CHAR), CONVERT(NEW.value_max, CHAR), NEW.id_change_set
		WHERE NOT (OLD.value_max <=> NEW.value_max)
	UNION
	-- Changed active
	SELECT NEW.id_metric, '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 ;
