-- Phase 7: Playbook 萃取功能 — playbooks 資料表
-- 建立時間: 2026-04-04 (台北時區)
-- 建立者: Claude Code (Phase 7 補齊 migration)
-- 對應設計: memory/project_playbook_design.md
-- 對應模型: apps/api/src/models/playbook.py

CREATE TABLE IF NOT EXISTS playbooks (
    -- 識別
    -- 2026-04-04 ogt: 首席架構師 Review — 加 PRIMARY KEY，移除多餘 UNIQUE
    playbook_id         VARCHAR(32)  PRIMARY KEY,

    -- 元資料
    name                VARCHAR(256) NOT NULL,
    description         TEXT         NOT NULL DEFAULT '',
    status              VARCHAR(32)  NOT NULL DEFAULT 'draft',   -- draft|approved|deprecated
    source              VARCHAR(32)  NOT NULL DEFAULT 'extracted', -- extracted|manual

    -- 症狀模式 (SymptomPattern JSON)
    symptom_pattern     JSONB        NOT NULL DEFAULT '{}',

    -- 修復步驟 (list[RepairStep] JSON)
    repair_steps        JSONB        NOT NULL DEFAULT '[]',
    estimated_duration_minutes INT  NOT NULL DEFAULT 5,

    -- 來源追溯
    source_incident_ids TEXT[]       NOT NULL DEFAULT '{}',
    ai_confidence       DECIMAL(4,3) NOT NULL DEFAULT 0.0,

    -- 統計數據
    success_count       INT          NOT NULL DEFAULT 0,
    failure_count       INT          NOT NULL DEFAULT 0,
    last_used_at        TIMESTAMPTZ,

    -- 人工標記
    approved_by         VARCHAR(128),
    approved_at         TIMESTAMPTZ,
    tags                TEXT[]       NOT NULL DEFAULT '{}',
    notes               TEXT,

    -- 時間軸
    created_at          TIMESTAMPTZ  NOT NULL DEFAULT NOW(),
    updated_at          TIMESTAMPTZ  NOT NULL DEFAULT NOW()
);

-- 索引
CREATE INDEX IF NOT EXISTS idx_playbooks_status
    ON playbooks(status);

CREATE INDEX IF NOT EXISTS idx_playbooks_tags
    ON playbooks USING GIN(tags);

CREATE INDEX IF NOT EXISTS idx_playbooks_alert_names
    ON playbooks USING GIN((symptom_pattern->'alert_names'));

CREATE INDEX IF NOT EXISTS idx_playbooks_source_incidents
    ON playbooks USING GIN(source_incident_ids);

CREATE INDEX IF NOT EXISTS idx_playbooks_created_at
    ON playbooks(created_at DESC);
