CREATE TABLE project_deltas (
    id INTEGER NOT NULL PRIMARY KEY,
    change_id INTEGER NOT NULL,
    project_id INTEGER NOT NULL,
    new INTEGER,
    title VARCHAR(1024),
    hub_id INTEGER,
    project_status_id INTEGER,
    FOREIGN KEY(id) REFERENCES deltas(id) ON DELETE CASCADE,
    FOREIGN KEY(project_status_id,project_id)
        REFERENCES project_status(id,project_id)
        ON DELETE CASCADE,
    FOREIGN KEY(hub_id) REFERENCES hubs(id) ON DELETE CASCADE
);

CREATE TRIGGER
    project_deltas_ai_1
AFTER INSERT ON
    project_deltas
FOR EACH ROW
BEGIN

    SELECT debug(
        NEW.id,
        NEW.project_id,
        NEW.title,
        NEW.project_status_id,
        NEW.hub_id
    );

    UPDATE
        changes
    SET
        ucount = ucount + 1
    WHERE
        id = NEW.change_id
    ;

    INSERT OR IGNORE INTO
        projects_tomerge(project_id) VALUES (NEW.project_id);

    UPDATE
        projects_tomerge
    SET
        title     = title + (NEW.title IS NOT NULL),
        project_status_id = project_status_id +
            (NEW.project_status_id IS NOT NULL)
    WHERE
        project_id = NEW.project_id
    ;


    -- TODO Could probably set a delete flag that triggers
    -- something in the project_hubs table to remove as needed

    /*
        We use OR IGNORE here because it can happen that a push to a
        hub succeeds remotely, but fails locally. If the push is
        attempted again it should still succeed. Also imgine if two
        users push to a repo - also no reason for failure.
    */
    INSERT OR IGNORE INTO
        project_hubs(
            project_id,
            hub_id
        )
    SELECT
        NEW.project_id,
        NEW.hub_id
    WHERE
        NEW.hub_id IS NOT NULL
    ;


    UPDATE
        change_nodes
    SET
        hub_change = hub_change + 1
    WHERE
        change_id = NEW.change_id AND node_id = NEW.project_id
    ;
END;


CREATE TRIGGER
    project_deltas_ad_1
AFTER DELETE ON
    project_deltas
FOR EACH ROW
BEGIN

    SELECT debug(
        OLD.project_id,
        OLD.project_status_id
    );


    INSERT OR IGNORE INTO
        projects_tomerge(project_id) VALUES (OLD.project_id);

    UPDATE
        projects_tomerge
    SET
        title     = title + (OLD.title IS NOT NULL),
        project_status_id = project_status_id
            + (OLD.project_status_id IS NOT NULL)
    WHERE
        project_id = OLD.project_id
    ;

END;
