CREATE TABLE link_topics_tomerge(
    link_topic_id INTEGER UNIQUE,
    topic_id INTEGER UNIQUE,
    title INTEGER DEFAULT 0,
    topic_status_id INTEGER NOT NULL DEFAULT 0,
    resolve INTEGER,
    CONSTRAINT link_topic_either_or CHECK(
        (link_topic_id IS NULL AND topic_id IS NOT NULL) OR
        (link_topic_id IS NOT NULL AND topic_id IS NULL)
    ),
    FOREIGN KEY(link_topic_id) REFERENCES link_topics(id) ON DELETE CASCADE,
    FOREIGN KEY(topic_id) REFERENCES topics(id) ON DELETE CASCADE
);


CREATE TRIGGER
    link_topics_tomerge_bu_2
BEFORE UPDATE OF
    resolve
ON
    link_topics_tomerge
FOR EACH ROW WHEN
    NEW.resolve = 1 AND
    OLD.topic_status_id != 0
BEGIN

    SELECT debug(
        OLD.link_topic_id,
        OLD.topic_id
    );

    UPDATE
        topics
    SET
        topic_status_id = (
            SELECT
                ltd.topic_status_id
            FROM
                link_topic_deltas ltd
            INNER JOIN
                changes c
            ON
                c.id = ltd.change_id
            WHERE
                ltd.topic_id = OLD.topic_id AND
                ltd.topic_status_id IS NOT NULL
            ORDER BY
                c.mtime DESC,
                c.uuid
            LIMIT
                1
        )
    WHERE
        id = OLD.topic_id
    ;

END;


CREATE TRIGGER
    link_topics_tomerge_bu_1
BEFORE UPDATE OF
    resolve
ON
    link_topics_tomerge
FOR EACH ROW WHEN
    NEW.resolve = 1 AND
    OLD.title != 0
BEGIN

    SELECT debug(
        OLD.link_topic_id,
        OLD.topic_id
    );

    UPDATE
        topics
    SET
        title = (
            SELECT
                ltd.title
            FROM
                link_topic_deltas ltd
            INNER JOIN
                changes c
            ON
                c.id = ltd.change_id
            WHERE
                ltd.link_topic_id = OLD.link_topic_id AND
                ltd.title IS NOT NULL
            ORDER BY
                c.mtime DESC,
                c.uuid
            LIMIT
                1
        )
    WHERE
        id IN (
            SELECT
                t.id
            FROM
                topics t
            WHERE
                t.link_topic_id = OLD.link_topic_id
        )
    ;

END;


CREATE TRIGGER
    link_topics_tomerge_au_1
AFTER UPDATE OF
    resolve
ON
    link_topics_tomerge
FOR EACH ROW WHEN
    NEW.resolve = 1
BEGIN

    SELECT debug(
        OLD.link_topic_id,
        OLD.topic_id
    );

    DELETE FROM
        link_topics_tomerge
    WHERE
        link_topic_id = OLD.link_topic_id OR
        topic_id = OLD.topic_id
    ;

END;
