-- =============================================================================
-- Phase 26: Incident → KM 完整鏈路補全
-- 2026-04-06 ogt: 修復三重死鎖 — 告警必須寫入 DB 並建立 KM
-- =============================================================================

-- 1. approval_records 加入 incident_id 欄位
ALTER TABLE approval_records
    ADD COLUMN IF NOT EXISTS incident_id TEXT;

CREATE INDEX IF NOT EXISTS idx_approval_records_incident_id
    ON approval_records (incident_id)
    WHERE incident_id IS NOT NULL;

-- 2. incidents 表確保有 source 欄位 (alertmanager / manual 等)
ALTER TABLE incidents
    ADD COLUMN IF NOT EXISTS source TEXT DEFAULT 'alertmanager';

-- 3. knowledge_entries 確保有 related_approval_id 欄位
ALTER TABLE knowledge_entries
    ADD COLUMN IF NOT EXISTS related_approval_id TEXT;

CREATE INDEX IF NOT EXISTS idx_knowledge_entries_related_approval
    ON knowledge_entries (related_approval_id)
    WHERE related_approval_id IS NOT NULL;

-- 完成確認
DO $$
BEGIN
    RAISE NOTICE 'Phase 26 migration completed: incident_id + source + related_approval_id';
END $$;
