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

-- name: DeprecateQuery :exec
INSERT INTO queryDeprecations (queryId) VALUES ($1);

-- name: IsQueryDeprecated :one
SELECT EXISTS (
    SELECT 1 FROM queryDeprecations where queryId = $1 and removedAt is not null
);

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

-- name: ListQueries :many
SELECT q.id, q.type, q.activeVersion, q.latestVersion, c.config, ARRAY_AGG(r.requiredQueryId) AS requiredIds
    FROM queries AS q
    LEFT JOIN queryConfigs AS c ON q.id = c.queryId
    LEFT JOIN requiredQueries AS r ON q.id = r.queryId
    WHERE c.addedVersion >= q.activeVersion
    and COALESCE(c.removedVersion, q.activeVersion - 1) < q.activeVersion
    and r.addedVersion >= q.activeVersion
    and COALESCE(r.removedVersion, q.activeVersion - 1) < q.activeVersion
    GROUP BY q.id, c.config;

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

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

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