
USE parts;

DROP TRIGGER IF EXISTS parts.before_insert_DOG_Personal_Best;
DROP TRIGGER IF EXISTS parts.before_update_DOG_Personal_Best;

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

DELIMITER //
CREATE TRIGGER parts.before_update_DOG_Personal_Best
BEFORE UPDATE ON parts.DOG_Personal_Best
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_Personal_Best_Audit (
		  id_personal_best
        , name_field
        , value_prev
        , value_new
        , id_change_set
    )
	-- Changed id_dog_command_link
	SELECT NEW.id_personal_best, 'id_dog_command_link', CONVERT(OLD.id_dog_command_link, CHAR), CONVERT(NEW.id_dog_command_link, CHAR), NEW.id_change_set
		WHERE NOT (OLD.id_dog_command_link <=> NEW.id_dog_command_link)
	UNION
    -- Changed is_achieved_using_button
	SELECT NEW.id_personal_best, 'is_achieved_using_button', CONVERT(CONVERT(OLD.is_achieved_using_button, SIGNED), CHAR), CONVERT(CONVERT(NEW.is_achieved_using_button, SIGNED), CHAR), NEW.id_change_set
		WHERE NOT (OLD.is_achieved_using_button <=> NEW.is_achieved_using_button)
	UNION
    -- Changed situation
	SELECT NEW.id_personal_best, 'situation', OLD.situation, NEW.situation, NEW.id_change_set
		WHERE NOT OLD.situation <=> NEW.situation
	UNION
	-- Changed quantity
	SELECT NEW.id_personal_best, 'quantity', CONVERT(OLD.quantity, CHAR), CONVERT(NEW.quantity, CHAR), NEW.id_change_set
		WHERE NOT (OLD.quantity <=> NEW.quantity)
	UNION
	-- Changed duration_seconds
	SELECT NEW.id_personal_best, 'duration_seconds', CONVERT(OLD.duration_seconds, CHAR), CONVERT(NEW.duration_seconds, CHAR), NEW.id_change_set
		WHERE NOT (OLD.duration_seconds <=> NEW.duration_seconds)
	UNION
    -- Changed active
	SELECT NEW.id_personal_best, '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 ;
