-- Manual Raw-to-rewrite flow is implemented in admin.py.
-- Non-target category (sort_order/category_id 18, tag НЦК) must not enter editorial review.

UPDATE app_settings
SET value_json = to_jsonb(
    CASE
      WHEN (value_json #>> '{}') LIKE '%category_id 18%'
        THEN value_json #>> '{}'
      ELSE (value_json #>> '{}') || E'\n- If the post is non-target content, choose category_id 18 ("Не целевой контент", tag "НЦК"); the app will reject it automatically.'
    END
),
updated_at = NOW()
WHERE key = 'ai_writer_contract';

UPDATE raw_posts
SET editorial_status='rejected',
    qualification_status='rejected',
    qualification_decision='rejected',
    qualification_model_decision='rejected',
    qualification_reason=COALESCE(NULLIF(qualification_reason, ''), 'AI writer selected non-target category'),
    qualification_reject_tag=COALESCE(NULLIF(qualification_reject_tag, ''), 'non_target_content'),
    editor_notes=COALESCE(NULLIF(editor_notes, ''), 'Отклонено AI: Не целевой контент'),
    reviewed_at=COALESCE(reviewed_at, NOW()),
    updated_at=NOW()
WHERE rewrite_status='ready'
  AND COALESCE(editorial_status, 'review')='review'
  AND (
    rewrite_category_id=18
    OR final_category_id=18
    OR lower(COALESCE(rewrite_category_tag, '')) IN ('нцк', 'nck')
    OR lower(COALESCE(final_category_tag, '')) IN ('нцк', 'nck')
    OR lower(COALESCE(rewrite_category, '')) = lower('Не целевой контент')
    OR lower(COALESCE(final_category, '')) = lower('Не целевой контент')
  );
