-- 377_domain_bucket.sql
-- ai_domain(반자유 AI 분류, 드리프트 존재)을 검색 스코프용 7버킷으로 결정적 롤업.
-- 축: ai_domain(routing/해석 축)의 coarsening — category(UI축) 아님 (feedback_category_vs_ai_domain_axis 준수).
-- 버킷: News / Safety / Law / Engineering / General / Philosophy / Programming.
-- STORED generated → 신규/재분류 문서도 ai_domain 붙으면 자동 버킷. ai_domain 원본 보존(하위 검색 유지).
-- 롤백: ALTER TABLE documents DROP COLUMN domain_bucket;
ALTER TABLE documents ADD COLUMN IF NOT EXISTS domain_bucket text
  GENERATED ALWAYS AS (
    CASE
      WHEN ai_domain LIKE 'News%' THEN 'News'
      WHEN ai_domain = '법령' OR ai_domain LIKE 'Industrial_Safety/Legislation%' THEN 'Law'
      WHEN ai_domain = 'Safety' OR ai_domain LIKE 'Safety/%'
           OR ai_domain LIKE 'Industrial_Safety%'
           OR ai_domain = 'Knowledge/Industrial_Safety' THEN 'Safety'
      WHEN ai_domain LIKE 'Engineering%' OR ai_domain = 'Knowledge/Engineering' THEN 'Engineering'
      WHEN ai_domain LIKE 'Philosophy%' THEN 'Philosophy'
      WHEN ai_domain LIKE 'Programming%' THEN 'Programming'
      ELSE 'General'
    END
  ) STORED;

CREATE INDEX IF NOT EXISTS documents_domain_bucket_idx
  ON documents (domain_bucket) WHERE deleted_at IS NULL;
