-- name: GetDocumentSummary :one
SELECT id, clientId, hash FROM documents WHERE id = $1;

-- name: GetDocumentExternal :one
WITH
docs AS (
  SELECT id, hash, clientId
  FROM documents
  WHERE id = @documentId
),
namedResults AS (
  SELECT
    q.name,
    dd.id,
    d.value
  FROM currentCollectorQueries AS q
  JOIN docs as dd on dd.clientId = q.clientId
  LEFT JOIN listValidDocumentResults(@documentId) AS d
    ON d.queryId = q.queryId and q.name is not null
)
SELECT
  d.id,
  c.externalId AS clientId,
  d.hash,
  COALESCE(jsonb_object_agg(r.name, r.value) FILTER (WHERE r.name IS NOT NULL), '{}') AS fields
FROM docs AS d
JOIN clients AS c ON c.id = d.clientId
LEFT JOIN namedResults AS r ON d.id = r.id
GROUP BY d.id, c.externalId, d.hash;

-- name: ListDocumentsByClientExternalId :many
WITH client as (
    SELECT id from clients where externalId = @clientId
)
SELECT d.id, d.hash
    from documents as d
    JOIN client as c on d.clientId = c.id;

-- name: CreateDocument :one
INSERT INTO documents (clientId, hash) VALUES ($1, $2) RETURNING id;

-- name: AddDocumentEntry :exec
INSERT INTO documentEntries (documentId, bucket, key) VALUES ($1, $2, $3);

-- name: GetDocumentEntry :one
SELECT documentId, bucket, key FROM documentEntries WHERE documentId = $1 ORDER BY id DESC LIMIT 1;

-- name: GetDocumentIDByHash :one
SELECT id FROM documents WHERE hash = $1 and clientId = $2;

-- name: ListDocumentIDsBatch :many
SELECT id, totalCount FROM listDocumentIDs(@clientId, @batchSize, @pageOffset);
