-- Add missing columns to existing processing_jobs table
-- This aligns the existing table with what the new code expects

-- Add attempts column (tracks retry attempts)
ALTER TABLE processing_jobs
ADD COLUMN IF NOT EXISTS attempts INTEGER NOT NULL DEFAULT 0;

-- Add max_attempts column (maximum retry attempts allowed)
ALTER TABLE processing_jobs
ADD COLUMN IF NOT EXISTS max_attempts INTEGER NOT NULL DEFAULT 3;

-- Add options column (stores processing configuration as JSON)
ALTER TABLE processing_jobs
ADD COLUMN IF NOT EXISTS options JSONB;

-- Add last_error_at column (timestamp of last error)
ALTER TABLE processing_jobs
ADD COLUMN IF NOT EXISTS last_error_at TIMESTAMP WITH TIME ZONE;

-- Add error column (current error message)
-- Note: This will coexist with error_message, we can migrate data later
ALTER TABLE processing_jobs
ADD COLUMN IF NOT EXISTS error TEXT;

-- Add result column (stores processing result as JSON)
ALTER TABLE processing_jobs
ADD COLUMN IF NOT EXISTS result JSONB;

-- Update status column to include new statuses
-- Note: Can't modify CHECK constraint easily, so we'll just document the new values
-- Existing statuses: pending, processing, completed, failed
-- New status: retrying

-- Create index on last_error_at for efficient retryable job queries
CREATE INDEX IF NOT EXISTS idx_processing_jobs_last_error_at
ON processing_jobs(last_error_at)
WHERE status = 'retrying';

-- Create index on attempts for monitoring
CREATE INDEX IF NOT EXISTS idx_processing_jobs_attempts
ON processing_jobs(attempts);

-- Comments for documentation
COMMENT ON COLUMN processing_jobs.attempts IS 'Number of processing attempts made';
COMMENT ON COLUMN processing_jobs.max_attempts IS 'Maximum number of retry attempts allowed';
COMMENT ON COLUMN processing_jobs.options IS 'Processing options and configuration (JSON)';
COMMENT ON COLUMN processing_jobs.last_error_at IS 'Timestamp of last error occurrence';
COMMENT ON COLUMN processing_jobs.error IS 'Current error message (new format)';
COMMENT ON COLUMN processing_jobs.result IS 'Processing result data (JSON)';

-- Verify the changes
SELECT
  column_name,
  data_type,
  is_nullable,
  column_default
FROM information_schema.columns
WHERE table_name = 'processing_jobs'
AND table_schema = 'public'
ORDER BY ordinal_position;
