CREATE TABLE link_topic_deltas (
    id INTEGER NOT NULL PRIMARY KEY,
    change_id INTEGER NOT NULL,
    link_topic_id INTEGER NOT NULL,
    topic_id INTEGER NOT NULL,
    title VARCHAR(1024),
    topic_status_id INTEGER,
    UNIQUE(change_id,topic_id), -- one change per change
    FOREIGN KEY(id) REFERENCES deltas(id),
    FOREIGN KEY(change_id) REFERENCES changes(id) ON DELETE CASCADE,
    FOREIGN KEY(link_topic_id) REFERENCES link_topics(id) ON DELETE CASCADE,
    FOREIGN KEY(topic_id) REFERENCES topics(id) ON DELETE CASCADE,
    FOREIGN KEY(topic_status_id)
        REFERENCES topic_status(id) ON DELETE CASCADE
);


CREATE INDEX
    link_topic_deltas_link_topic_id_title
ON
    link_topic_deltas(link_topic_id,title)
WHERE
    title IS NOT NULL
;


CREATE INDEX
    link_topic_deltas_topic_id_topic_status_id
ON
    link_topic_deltas(topic_id,topic_status_id)
WHERE
    topic_status_id IS NOT NULL
;


CREATE TRIGGER
    link_topic_deltas_ai_1
AFTER INSERT ON
    link_topic_deltas
FOR EACH ROW
BEGIN

    SELECT debug(
        NEW.change_id,
        NEW.topic_id,
        NEW.topic_status_id,
        NEW.title
    );


    INSERT OR IGNORE INTO
        link_topics_tomerge(topic_id)
    SELECT
        NEW.topic_id
    WHERE
        NEW.topic_status_id IS NOT NULL
    ;


    UPDATE
        link_topics_tomerge
    SET
        topic_status_id = topic_status_id + (NEW.topic_status_id IS NOT NULL)
    WHERE
        topic_id = NEW.topic_id
    ;


    INSERT OR IGNORE INTO
        link_topics_tomerge(link_topic_id)
    SELECT
        NEW.link_topic_id
    WHERE
        NEW.title IS NOT NULL
    ;


    UPDATE
        link_topics_tomerge
    SET
        title = title + (NEW.title IS NOT NULL)
    WHERE
        link_topic_id = NEW.link_topic_id
    ;


    UPDATE
        change_nodes
    SET
        project_change = project_change + 1
    WHERE
        change_id = NEW.change_id AND node_id IN (
            SELECT
                t.id
            FROM
                topics t
            WHERE
                t.link_topic_id = NEW.link_topic_id
        )
    ;

END;


CREATE TRIGGER
    link_topic_deltas_ad_1
AFTER DELETE ON
    link_topic_deltas
FOR EACH ROW
BEGIN

    SELECT debug(
        OLD.change_id,
        OLD.topic_id,
        OLD.topic_status_id,
        OLD.title
    );


    INSERT OR IGNORE INTO
        link_topics_tomerge(topic_id)
    SELECT
        OLD.topic_id
    WHERE
        OLD.topic_status_id IS NOT NULL
    ;


    UPDATE
        link_topics_tomerge
    SET
        topic_status_id = topic_status_id + (OLD.topic_status_id IS NOT NULL)
    WHERE
        topic_id = OLD.topic_id
    ;


    INSERT OR IGNORE INTO
        link_topics_tomerge(link_topic_id)
    SELECT
        OLD.link_topic_id
    WHERE
        OLD.title IS NOT NULL
    ;


    UPDATE
        link_topics_tomerge
    SET
        title = title + (OLD.title IS NOT NULL)
    WHERE
        link_topic_id = OLD.link_topic_id
    ;

END;
