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

-- name: ListDocumentsByClientId :many
WITH docs as (
    SELECT id from documents where clientId = @clientId
),
entries as (
    SELECT
        de.documentId,
        de.bucket,
        de.key,
        ROW_NUMBER() OVER (PARTITION BY de.documentId ORDER BY de.id DESC) as rowNumber
    FROM docs d
    JOIN documentEntries de on d.id = de.documentId
)
SELECT documentId as id, bucket, key from entries WHERE rowNumber = 1;

-- 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);
