-- name: GetQueryConfig :one
SELECT id, config FROM queryConfigs where queryId = $1 and addedVersion >= $2 and COALESCE(removedVersion, $2 - 1) < $2;

-- name: GetQuery :one
SELECT * FROM fullActiveQueries WHERE id = $1;

-- name: GetQueryWithVersion :one
SELECT DISTINCT q.id, q.type, q.activeVersion, q.latestVersion, coalesce(c.config, null) as config, ARRAY_AGG(DISTINCT r.requiredQueryId)::uuid[] as requiredIds
    FROM queries AS q
    LEFT JOIN queryConfigs AS c ON q.id = c.queryId
        and $2 >= c.addedVersion
        and $2 < COALESCE(c.removedVersion, $2 + 1)
    LEFT JOIN requiredQueries AS r ON q.id = r.queryId
        and $2 >= r.addedVersion
        and $2 < COALESCE(r.removedVersion, $2 + 1)
    WHERE q.id = $1
    GROUP BY q.id, q.type, q.activeversion, q.latestversion, c.config;

-- name: ListQueries :many
SELECT * FROM fullActiveQueries;

-- name: ListQueriesById :many
SELECT * FROM fullActiveQueries WHERE id = any($1);

-- name: CreateQuery :one
INSERT INTO queries (type) VALUES ($1) RETURNING id;

-- name: UpdateQuery :exec
UPDATE queries SET activeVersion = $1, latestVersion = $2 WHERE id = $3;

-- name: AddRequiredQuery :exec
INSERT INTO requiredQueries (queryId, requiredQueryId, addedVersion) VALUES ($1, $2, $3);

-- name: RemoveRequiredQuery :exec
UPDATE requiredQueries SET removedVersion = $1 WHERE requiredQueryId = $2 and queryId = $3 and removedVersion is null;

-- name: AddQueryConfig :exec
INSERT INTO queryConfigs (queryId, config, addedVersion) VALUES ($1, $2, $3);

-- name: RemoveQueryConfig :exec
UPDATE queryConfigs SET removedVersion = $1 WHERE queryId = $2 and removedVersion is null;

-- name: AllQueriesExist :one
SELECT COUNT(*) = COUNT(DISTINCT id) AS all_exist
    FROM unnest($1::uuid[]) AS input_id
    LEFT JOIN queries ON input_id = queries.id;

-- name: IsQueryInDependencyTree :one
SELECT EXISTS (
    SELECT 1 FROM queryActiveDependencies WHERE id = any($1) and requiredQueryId = $2 or $2 = any($1)
);