CREATE TABLE node_deltas (
    id INTEGER NOT NULL PRIMARY KEY,
    change_id INTEGER NOT NULL,
    node_id INTEGER NOT NULL,
    parent_id INTEGER,
    name VARCHAR(1024), -- TODO same constraint as nodes nable
    FOREIGN KEY(id) REFERENCES deltas(id) ON DELETE CASCADE,
    FOREIGN KEY(change_id) REFERENCES changes(id) ON DELETE CASCADE,
    FOREIGN KEY(node_id) REFERENCES nodes(id) ON DELETE CASCADE,
    FOREIGN KEY(parent_id) REFERENCES nodes(id) ON DELETE CASCADE
);


CREATE TRIGGER
    node_deltas_ai_1
AFTER INSERT ON
    node_deltas
FOR EACH ROW
BEGIN

    SELECT debug(
        NEW.id,
        NEW.change_id,
        NEW.node_id,
        NEW.parent_id,
        NEW.name
    );

    UPDATE
        nodes
    SET
        last_change_id = NEW.change_id
    WHERE
        id = NEW.node_id
    ;


    INSERT OR IGNORE INTO
        nodes_tomerge(
            node_id
        )
    VALUES(
        NEW.node_id
    );


    UPDATE
        nodes_tomerge
    SET
        parent_id = parent_id + (NEW.parent_id IS NOT NULL),
        name = name + (NEW.name IS NOT NULL)
    WHERE
        node_id = NEW.node_id
    ;

    INSERT INTO
        change_nodes(
            change_id,
            node_id
        )
    VALUES(
        NEW.change_id,
        NEW.node_id
    );

END;


CREATE TRIGGER
    nodes_deltas_bd_1
BEFORE DELETE ON
    node_deltas
FOR EACH ROW WHEN
    EXISTS (
        SELECT
            1
        FROM
            nodes n
        WHERE
            n.id = OLD.node_id AND
            n.last_change_id = OLD.change_id AND
            n.first_change_id != OLD.change_id
    )
BEGIN

    SELECT debug(
        OLD.node_id
    );

    UPDATE
        nodes
    SET
        last_change_id = (
            SELECT
                MAX(ct.child)
            FROM
                nodes n
            INNER JOIN
                changes_tree ct
            ON
                ct.parent = n.first_change_id AND
                ct.child != OLD.change_id
            WHERE
                n.id = OLD.node_id
        )
    WHERE
        id = OLD.node_id
    ;

END;


CREATE TRIGGER
    node_deltas_ad_1
AFTER DELETE ON
    node_deltas
FOR EACH ROW
BEGIN

    SELECT debug(
        OLD.id,
        OLD.name
    );

    INSERT OR IGNORE INTO
        nodes_tomerge(node_id)
    VALUES
        (OLD.node_id)
    ;

    UPDATE
        nodes_tomerge
    SET
        parent_id = parent_id + (OLD.parent_id IS NOT NULL),
        name = name + (OLD.name IS NOT NULL)
    WHERE
        node_id = OLD.node_id
    ;

END;
