ALTER TABLE raw_posts
  ADD COLUMN IF NOT EXISTS editorial_status TEXT,
  ADD COLUMN IF NOT EXISTS final_text TEXT,
  ADD COLUMN IF NOT EXISTS final_category TEXT,
  ADD COLUMN IF NOT EXISTS final_category_tag TEXT,
  ADD COLUMN IF NOT EXISTS final_source_tag TEXT,
  ADD COLUMN IF NOT EXISTS editor_notes TEXT,
  ADD COLUMN IF NOT EXISTS regeneration_prompt TEXT,
  ADD COLUMN IF NOT EXISTS reviewed_by BIGINT REFERENCES admin_users(id) ON DELETE SET NULL,
  ADD COLUMN IF NOT EXISTS reviewed_at TIMESTAMPTZ,
  ADD COLUMN IF NOT EXISTS edited_at TIMESTAMPTZ;

UPDATE raw_posts
SET editorial_status = 'review'
WHERE editorial_status IS NULL
  AND rewrite_status = 'ready';

UPDATE raw_posts
SET final_text = rewritten_text,
    final_category = rewrite_category,
    final_category_tag = rewrite_category_tag,
    final_source_tag = rewrite_source_tag
WHERE rewrite_status = 'ready'
  AND final_text IS NULL;

CREATE INDEX IF NOT EXISTS idx_raw_posts_editorial_status
ON raw_posts(editorial_status, rewritten_at DESC, id)
WHERE rewrite_status = 'ready';

CREATE INDEX IF NOT EXISTS idx_raw_posts_final_category
ON raw_posts(final_category)
WHERE final_category IS NOT NULL;
