CREATE TABLE project_hubs(
    project_id INTEGER NOT NULL,
    hub_id INTEGER NOT NULL,
    PRIMARY KEY(project_id,hub_id),
    FOREIGN KEY(project_id) REFERENCES projects(id) ON DELETE CASCADE,
    FOREIGN KEY(hub_id) REFERENCES hubs(id) ON DELETE CASCADE
);


-- TODO: some of hrp is covered by projects_tree since hubs became
-- projects
CREATE TRIGGER
    project_hubs_ai_1
AFTER INSERT ON
    project_hubs
FOR EACH ROW
BEGIN

    UPDATE
        projects
    SET
        default_hub_id = NEW.hub_id
    WHERE
        id = NEW.project_id AND default_hub_id IS NULL
    ;

    -- Pre-existing project identities
    INSERT OR IGNORE INTO
        hub_entities(
            hub_id,
            entity_id
        )
    SELECT DISTINCT
        NEW.hub_id,
        e.id
    FROM
        nodes_tree nt
    INNER JOIN
        nodes n
    ON
        n.id = nt.child AND
        n.kind IN (
            'project',
            'project_status',
            'task_status',
            'issue_status'
        )
    INNER JOIN
        changes_tree ct
    ON
        ct.parent = n.first_change_id 
    INNER JOIN
        changes c
    ON
        c.id = ct.child
    -- We force the join with entities because inside some transactions
    -- c.identity_id does not point to a valid entity (it is -1) for
    -- changes that haven't been resolved yet.
    INNER JOIN
        entities e
    ON
        e.id = c.identity_id
    WHERE
        nt.parent = NEW.project_id
    ;

    -- Pre-existing project changes
    INSERT OR IGNORE INTO
        hub_related_changes(
            hub_id,
            prefix,
            change_id,
            sha1
        )
    SELECT DISTINCT
        NEW.hub_id,
        SUBSTR(c.uuid, 1, 1),
        c.id,
        c.uuid
    FROM
        nodes_tree nt
    INNER JOIN
        nodes n
    ON
        n.id = nt.child AND
        n.kind IN (
            'project',
            'project_status',
            'task_status',
            'issue_status'
        )
    INNER JOIN
        changes_tree ct
    ON
        ct.parent = n.first_change_id 
    INNER JOIN
        changes c
    ON
        c.id = ct.child
    -- We force the join with entities because inside some transactions
    -- c.identity_id does not point to a valid entity (it is -1) for
    -- changes that haven't been resolved yet.
    INNER JOIN
        entities e
    ON
        e.id = c.identity_id
    WHERE
        nt.parent = NEW.project_id
    ;

END;
