ALTER TABLE raw_posts
  ADD COLUMN IF NOT EXISTS qualification_model_decision TEXT;

UPDATE raw_posts rp
SET qualification_model_decision = item->>'decision'
FROM ai_qualification_batches b,
     jsonb_array_elements(COALESCE(b.response_json->'results', '[]'::jsonb)) AS item
WHERE rp.qualification_batch_id = b.id
  AND (item->>'id')::bigint = rp.id
  AND rp.qualification_model_decision IS NULL
  AND item ? 'decision';

CREATE INDEX IF NOT EXISTS idx_raw_posts_qualification_model_decision
ON raw_posts(qualification_model_decision)
WHERE qualification_model_decision IS NOT NULL;
