-- name: IsDocumentTextExtracted :one
SELECT EXISTS(
    SELECT 1
        FROM documentTextExtractions AS dc
        JOIN documents AS d ON d.id = dc.documentId
        LEFT JOIN collectors as c ON d.jobId = c.jobId
        LEFT JOIN collectorCodeVersions as cv ON c.id = cv.collectorId
        WHERE dc.documentId = $1 and dc.version >= coalesce(cv.minTextVersion, 1)
);

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

-- name: GetDocumentTextEntry :one
SELECT dc.documentId, dc.bucket, dc.key, dc.version
    FROM documentTextExtractions AS dc
    JOIN documents AS d ON d.id = dc.documentId
    LEFT JOIN collectors as c ON d.jobId = c.jobId
    LEFT JOIN collectorCodeVersions as cv ON c.id = cv.collectorId
    WHERE dc.documentId = $1 and dc.version >= coalesce(cv.minTextVersion, 1)
    ORDER BY d.id DESC LIMIT 1;