-- name: CreateBatchUpload :one
INSERT INTO batch_uploads (client_id, original_filename, total_documents)
VALUES ($1, $2, $3) RETURNING id;

-- name: CreateBatchUploadWithStorage :one
INSERT INTO batch_uploads (
    client_id, 
    original_filename, 
    total_documents, 
    status,
    archive_bucket, 
    archive_key,
    file_size_bytes
) VALUES ($1, $2, $3, $4::batch_status, $5, $6, $7) 
RETURNING id, created_at;

-- name: GetBatchUpload :one
SELECT id, client_id, original_filename, total_documents, processed_documents, 
       failed_documents, invalid_type_documents, status, progress_percent,
       failed_filenames, created_at, completed_at
FROM batch_uploads 
WHERE id = $1 AND client_id = $2;

-- name: GetBatchUploadWithStorage :one
SELECT id, client_id, original_filename, total_documents, 
       processed_documents, failed_documents, invalid_type_documents,
       status, archive_bucket, archive_key, file_size_bytes,
       failed_filenames, created_at, completed_at
FROM batch_uploads 
WHERE id = $1 AND client_id = $2;

-- name: ListBatchUploads :many
SELECT id, client_id, original_filename, total_documents, processed_documents, 
       failed_documents, invalid_type_documents, status, progress_percent,
       created_at, completed_at
FROM batch_uploads 
WHERE client_id = $1
ORDER BY created_at DESC
LIMIT $2 OFFSET $3;

-- name: UpdateBatchProgress :exec
UPDATE batch_uploads 
SET processed_documents = $2, 
    failed_documents = $3, 
    invalid_type_documents = $4,
    progress_percent = $5
WHERE id = $1;

-- name: UpdateBatchStatus :exec
UPDATE batch_uploads 
SET status = $2::batch_status,
    completed_at = CASE WHEN $2::batch_status IN ('completed', 'failed', 'cancelled') THEN NOW() ELSE NULL END
WHERE id = $1;

-- name: AddFailedFilename :exec
UPDATE batch_uploads 
SET failed_filenames = failed_filenames || jsonb_build_array($2::text)
WHERE id = $1;

-- name: CancelBatchUpload :exec
UPDATE batch_uploads 
SET status = 'cancelled',
    completed_at = NOW()
WHERE id = $1 AND client_id = $2 AND status = 'processing';

-- name: GetDocumentsByBatchId :many
SELECT id, clientId, hash 
FROM documents 
WHERE batch_id = $1;

-- name: CountDocumentsByBatchId :one
SELECT COUNT(*) as count
FROM documents 
WHERE batch_id = $1;

-- name: GetUnprocessedBatches :many
SELECT id, client_id, original_filename, total_documents, 
       processed_documents, failed_documents, invalid_type_documents,
       status, progress_percent, created_at, completed_at
FROM batch_uploads 
WHERE status = 'processing'
ORDER BY created_at ASC;