-- name: IsDocumentClean :one
SELECT EXISTS(
    SELECT 1
        FROM documentCleans AS dc
        JOIN documents AS d ON d.id = dc.documentId
        LEFT JOIN collectors as c ON d.jobId = c.jobId
        LEFT JOIN collectorCurrentActiveVersions as av on c.id = av.collectorId
        LEFT JOIN collectorMinCleanVersions AS ccv ON c.id = ccv.collectorId
            and isInVersion(av.id, ccv.addedVersion, ccv.removedVersion)
        WHERE dc.documentId = $1 and dc.version >= coalesce(ccv.versionId, 1)
);

-- name: AddDocumentCleanEntry :exec
INSERT INTO documentCleans (documentId, version, bucket, key) VALUES ($1, $2, $3, $4);

-- name: GetDocumentCleanEntry :one
SELECT dc.documentId, dc.bucket, dc.key, dc.version
    FROM documentCleans AS dc
    JOIN documents AS d ON d.id = dc.documentId
    LEFT JOIN collectors as c ON d.jobId = c.jobId
    LEFT JOIN collectorCurrentActiveVersions as av on c.id = av.collectorId
    LEFT JOIN collectorMinCleanVersions AS ccv ON c.id = ccv.collectorId
        and isInVersion(av.id, ccv.addedVersion, ccv.removedVersion)
    WHERE dc.documentId = $1 and dc.version >= coalesce(ccv.versionId, 1)
    ORDER BY d.id DESC LIMIT 1;