-- Create jobs for all documents stuck in processing_llm status
-- This will find all stuck documents and create jobs for them

-- First, find all stuck documents
SELECT 
  id,
  user_id,
  status,
  original_file_name,
  updated_at
FROM documents
WHERE status = 'processing_llm'
ORDER BY updated_at ASC;

-- Then create jobs for each document (replace DOCUMENT_ID and USER_ID)
-- Run this for each document found above:

INSERT INTO processing_jobs (
  document_id,
  user_id,
  status,
  attempts,
  max_attempts,
  options,
  created_at
) 
SELECT 
  id as document_id,
  user_id,
  'pending' as status,
  0 as attempts,
  3 as max_attempts,
  '{"strategy": "document_ai_agentic_rag"}'::jsonb as options,
  NOW() as created_at
FROM documents
WHERE status = 'processing_llm'
  AND id NOT IN (SELECT document_id FROM processing_jobs WHERE status IN ('pending', 'processing', 'retrying'))
RETURNING id, document_id, status, created_at;

-- Verify jobs were created
SELECT 
  pj.id as job_id,
  pj.document_id,
  pj.status as job_status,
  d.original_file_name,
  pj.created_at
FROM processing_jobs pj
JOIN documents d ON d.id = pj.document_id
WHERE pj.status = 'pending'
ORDER BY pj.created_at DESC;

