-- Phase 25 P1: Knowledge Auto-Harvesting — symptoms_hash 欄位
-- 用於 Anti-Pattern 閉環攔截的確定性症狀 hash
-- 建立時間: 2026-04-04 (台北時區)
-- 建立者: Claude Code (Phase 25 P1)
--
-- 執行方式: psql -h 192.168.0.188 -U awoooi -d awoooi -f phase8_symptoms_hash.sql

-- 1. knowledge_entries 表新增 symptoms_hash 欄位
ALTER TABLE knowledge_entries
    ADD COLUMN IF NOT EXISTS symptoms_hash VARCHAR(16);

-- 2. 建立 index 加速 Anti-Pattern 閘門查詢
--    查詢條件: entry_type='anti_pattern' AND symptoms_hash=:hash AND created_at>=:cutoff
CREATE INDEX IF NOT EXISTS idx_knowledge_anti_pattern_hash
    ON knowledge_entries (entry_type, symptoms_hash, created_at)
    WHERE entry_type = 'anti_pattern' AND symptoms_hash IS NOT NULL;

-- 3. EntryStatus 新增 PUBLISHED（用於 ANTI_PATTERN 直接發布）
--    PostgreSQL CHECK constraint 需要重建（若有的話）
--    若無 constraint，PostgreSQL 的 VARCHAR 欄位可直接存入任意值，無需 ALTER。
--    確認 status 欄位是否有 CHECK constraint:
-- SELECT conname, consrc FROM pg_constraint
--   WHERE conrelid = 'knowledge_entries'::regclass AND contype = 'c';

-- 若有 CHECK constraint（如 status IN ('draft', 'review', 'approved', 'archived')），
-- 需執行以下（請先確認 constraint 名稱）：
-- ALTER TABLE knowledge_entries DROP CONSTRAINT IF EXISTS knowledge_entries_status_check;
-- ALTER TABLE knowledge_entries ADD CONSTRAINT knowledge_entries_status_check
--   CHECK (status IN ('draft', 'review', 'approved', 'archived', 'published'));

-- 安全執行版本（自動處理 CHECK constraint）：
DO $$
DECLARE
    v_conname text;
BEGIN
    SELECT conname INTO v_conname
    FROM pg_constraint
    WHERE conrelid = 'knowledge_entries'::regclass AND contype = 'c' AND conname LIKE '%status%';

    IF v_conname IS NOT NULL THEN
        EXECUTE format('ALTER TABLE knowledge_entries DROP CONSTRAINT %I', v_conname);
        ALTER TABLE knowledge_entries ADD CONSTRAINT knowledge_entries_status_check
            CHECK (status IN ('draft', 'review', 'approved', 'archived', 'published'));
        RAISE NOTICE 'Updated status CHECK constraint: % → added published', v_conname;
    ELSE
        RAISE NOTICE 'No status CHECK constraint found, skipping';
    END IF;
END $$;
