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

-- name: GetCleanEntry :one
SELECT id, documentId, bucket, key, version, hash, mimetype, fail, clientId
    FROM currentCleanEntries
    WHERE id = @cleanId;

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

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

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

-- name: GetMostRecentDocumentCleanEntry :one
WITH cleans as (
    SELECT id, documentId, bucket, key, hash, mimetype, fail
    FROM documentCleans dc
    WHERE documentId = @documentId ORDER BY id DESC
)
SELECT
    dc.id,
    dc.documentId,
    dc.bucket,
    dc.key,
    dce.version,
    dc.hash,
    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;
