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

-- name: GetDocumentExternal :one
-- Query functionality has been removed. See remove_query_plan.md for details.
SELECT
  id,
  clientId,
  hash
FROM documents
WHERE id = @documentId;

-- name: ListDocumentsByClient :many
SELECT id, hash from documents where clientId = @clientId;

-- name: ListDocumentsByBatch :many
SELECT id, hash, filename from documents where batch_id = @batch_id;

-- name: CreateDocument :one
INSERT INTO documents (clientId, hash, batch_id, filename, folderId, originalPath, file_size_bytes) VALUES ($1, $2, $3, $4, $5, $6, $7) 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);

-- name: AddDocumentUpload :exec
INSERT INTO documentUploads (id, clientId, bucket, key, part, createdAt, filename, batch_id, folder_id) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9);

-- name: GetDocumentUploadByKey :one
SELECT id, clientId, bucket, key, part, createdAt, filename, batch_id, folder_id FROM documentUploads WHERE bucket = $1 AND key = $2 LIMIT 1;

-- name: ListDocumentUploads :many
SELECT id, clientId, bucket, key, part, createdAt, filename, batch_id, folder_id FROM documentUploads WHERE clientId = $1 ORDER BY createdAt;

-- name: GetDocumentUploadCurrentPart :one
WITH client as (
    select clientId from clients where clientId = @clientId
),
parts as (
    SELECT docs.part
        FROM client as c
        JOIN documentUploads as docs on docs.clientId = c.clientId
        WHERE date(docs.createdAt) = date(@queryDate)
),
max_part as (
    SELECT COALESCE(max(part), 0) as max_part_num FROM parts
)
SELECT
    COALESCE(p.part, 0)::unsignedsmallint as part,
    COUNT(p.part) as count
FROM parts p
RIGHT JOIN max_part mp ON p.part = mp.max_part_num
GROUP BY p.part;

-- name: GetDocumentEnriched :one
-- Retrieves a document with extended metadata including folder and filename
SELECT
    d.id,
    d.clientId,
    d.hash,
    d.folderId,
    d.filename,
    d.originalPath,
    d.file_size_bytes
FROM documents d
WHERE d.id = $1;
