CREATE TABLE project_changes(
    project_id INTEGER NOT NULL,
    change_id INTEGER NOT NULL,
    map_entities INTEGER NOT NULL DEFAULT 0,
    UNIQUE(change_id,project_id) ON CONFLICT IGNORE
    CONSTRAINT map_entities_constaint CHECK (
        map_entities = 0 OR map_entities = 1
    ),
    FOREIGN KEY(change_id) REFERENCES changes(id) ON DELETE CASCADE,
    FOREIGN KEY(project_id) REFERENCES projects(id) ON DELETE CASCADE
);

CREATE INDEX
    project_changes_project_id
ON
    project_changes(project_id)
;

CREATE INDEX
    idx_project_changes_map_entities_change_id
ON
    project_changes(change_id,map_entities)
WHERE
    map_entities = 0
;

/*
    Project-only changes must also be recorded as hub-related changes.
*/

CREATE TRIGGER
    project_changes_ai_1
AFTER INSERT ON
    project_changes
FOR EACH ROW
BEGIN
    SELECT debug(
        NEW.project_id,
        NEW.change_id
    );


    INSERT INTO
        hub_related_changes(
            hub_id,
            change_id,
            merkled
        )
    SELECT
        hrp.hub_id,
        NEW.change_id,
        c.valid
    FROM
        hub_related_projects hrp
    INNER JOIN
        changes c
    ON
        c.id = NEW.change_id
    WHERE
        hrp.project_id = NEW.project_id
    ;
END;


CREATE TRIGGER
    project_changes_au_1
AFTER UPDATE OF
    map_entities
ON
    project_changes
FOR EACH ROW WHEN
    OLD.map_entities = 0 AND NEW.map_entities = 1
BEGIN
    SELECT debug(
        OLD.project_id,
        OLD.change_id
    );

    INSERT INTO
        project_entities(
            project_id,
            entity_id
        )
    SELECT
        NEW.project_id,
        c.identity_id
    FROM
        changes c
    WHERE
        c.id = OLD.change_id
    ;

END;

-- TODO deletes?
