-- name: HasDocumentCleanEntry :one
SELECT EXISTS(
    SELECT 1 FROM currentCleanEntries WHERE documentId = @documentId
);

-- name: GetDocumentCleanEntry :one
SELECT id, documentId, bucket, key, version, mimetype, fail
    FROM currentCleanEntries
    WHERE documentId = @documentId;

-- name: AddDocumentClean :one
INSERT INTO documentCleans (documentId, bucket, key, mimetype, fail) VALUES ($1, $2, $3, $4, $5) returning id;

-- name: AddDocumentCleanEntry :exec
INSERT INTO documentCleanEntries (cleanId, version) VALUES ($1, $2);

-- name: GetMostRecentDocumentCleanEntry :one
WITH cleans as (
    SELECT id, documentId, bucket, key, mimetype, fail
    FROM documentCleans dc
    WHERE documentId = @documentId ORDER BY id DESC
)
SELECT
    dc.id,
    dc.documentId,
    dc.bucket,
    dc.key,
    dce.version,
    dc.mimetype,
    dc.fail
FROM cleans dc
JOIN documentCleanEntries dce ON dc.id = dce.cleanId
ORDER BY dc.id DESC, dce.id DESC
LIMIT 1;
