
USE parts;

DROP TRIGGER IF EXISTS parts.before_insert_DOG_Dog_Breed_Link;
DROP TRIGGER IF EXISTS parts.before_update_DOG_Dog_Breed_Link;

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

DELIMITER //
CREATE TRIGGER parts.before_update_DOG_Dog_Breed_Link
BEFORE UPDATE ON parts.DOG_Dog_Breed_Link
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_Dog_Breed_Link_Audit (
		  id_link
        , name_field
        , value_prev
        , value_new
        , id_change_set
    )
	-- Changed id_dog
	SELECT NEW.id_link, 'id_dog', CONVERT(OLD.id_dog, CHAR), CONVERT(NEW.id_dog, CHAR), NEW.id_change_set
		WHERE NOT (OLD.id_dog <=> NEW.id_dog)
    UNION
	-- Changed id_breed
	SELECT NEW.id_link, 'id_breed', CONVERT(OLD.id_breed, CHAR), CONVERT(NEW.id_breed, CHAR), NEW.id_change_set
		WHERE NOT (OLD.id_breed <=> NEW.id_breed)
    UNION
	-- Changed lineage_ratio
	SELECT NEW.id_link, 'lineage_ratio', CONVERT(OLD.lineage_ratio, CHAR), CONVERT(NEW.lineage_ratio, CHAR), NEW.id_change_set
		WHERE NOT (OLD.lineage_ratio <=> NEW.lineage_ratio)
    UNION
	-- Changed active
	SELECT NEW.id_link, '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 ;
