CREATE TYPE queryType AS ENUM ('context_full', 'json_extractor');

CREATE TABLE queries (
    id uuid primary key DEFAULT uuid_generate_v7(),
    type queryType not null
);

CREATE TABLE queryVersions (
    queryId uuid not null,
    id int not null,
    addedAt timestamp not null default current_timestamp,
    primary key (id, queryId),
    foreign key (queryId) references queries(id)
);

CREATE OR REPLACE FUNCTION setQueryVersionNumber()
RETURNS TRIGGER AS $$
BEGIN
    SELECT COALESCE(MAX(id), 0) + 1
    INTO NEW.id
    FROM queryVersions
    WHERE queryId = NEW.queryId;
    
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER setQueryVersionNumberTrigger
BEFORE INSERT ON queryVersions
FOR EACH ROW
EXECUTE FUNCTION setQueryVersionNumber();

CREATE TABLE queryActiveVersions (
    id uuid primary key DEFAULT uuid_generate_v7(),
    queryId uuid not null,
    versionId int not null,
    foreign key (queryId, versionId) references queryVersions(queryId, id)
);

CREATE TABLE requiredQueries (
    id uuid primary key DEFAULT uuid_generate_v7(),
    queryId uuid not null,
    requiredQueryId uuid not null,
    addedVersion int not null,
    removedVersion int,
    foreign key (queryId) references queries(id),
    foreign key (requiredQueryId) references queries(id),
    foreign key (queryId, addedVersion) references queryVersions(queryId, id),
    foreign key (queryId, removedVersion) references queryVersions(queryId, id),
    unique (queryId, requiredQueryId, removedVersion)
);

CREATE TABLE queryConfigs (
    id uuid primary key DEFAULT uuid_generate_v7(),
    queryId uuid not null,
    config jsonb not null,
    addedVersion int not null,
    removedVersion int,
    foreign key (queryId) references queries(id),
    foreign key (queryId, addedVersion) references queryVersions(queryId, id),
    foreign key (queryId, removedVersion) references queryVersions(queryId, id),
    unique (queryId, removedVersion)
);

CREATE OR REPLACE FUNCTION removeQueryConfig()
RETURNS TRIGGER AS $$
BEGIN
    UPDATE queryConfigs 
        SET removedVersion = NEW.addedVersion
        WHERE queryId = NEW.queryId and removedVersion is null;
    
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER removeQueryConfigTrigger
BEFORE INSERT ON queryConfigs
FOR EACH ROW
EXECUTE FUNCTION removeQueryConfig();