
USE fetchmetrics;

DROP TRIGGER IF EXISTS fetchmetrics.before_insert_DOG_Command_Modality;
DROP TRIGGER IF EXISTS fetchmetrics.before_update_DOG_Command_Modality;

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

DELIMITER //
CREATE TRIGGER fetchmetrics.before_update_DOG_Command_Modality
BEFORE UPDATE ON fetchmetrics.DOG_Command_Modality
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_Command_Modality_Audit (
		  id_command_modality
        , name_field
        , value_prev
        , value_new
        , id_change_set
    )
    -- Changed code
	SELECT NEW.id_command_modality, 'code', OLD.code, NEW.code, NEW.id_change_set
		WHERE NOT OLD.code <=> NEW.code
	UNION
    -- Changed name
	SELECT NEW.id_command_modality, 'name', OLD.name, NEW.name, NEW.id_change_set
		WHERE NOT OLD.name <=> NEW.name
    UNION
	-- Changed active
	SELECT NEW.id_command_modality, '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 ;
