-- Phase 28 (ADR-067): RAG 知識庫 pgvector 向量表
-- 2026-04-10 Claude Sonnet 4.6 Asia/Taipei
-- 前置: pgvector 0.8.2 已安裝於 awoooi_prod ✅
-- 索引: 初期線性搜尋 (< 100 筆)；超過 100 筆後執行 CREATE INDEX ivfflat

CREATE EXTENSION IF NOT EXISTS vector;

CREATE TABLE IF NOT EXISTS rag_chunks (
    id          SERIAL PRIMARY KEY,
    source      TEXT NOT NULL,               -- 來源: "playbook", "incident", "runbook", "adr"
    source_id   TEXT,                        -- 來源 ID (playbook_id / incident_id 等)
    title       TEXT NOT NULL,               -- 標題 / 檔名
    chunk_text  TEXT NOT NULL,               -- 原始文字片段
    embedding   vector(768),                 -- nomic-embed-text 768維向量
    metadata    JSONB DEFAULT '{}',          -- 額外 metadata
    created_at  TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at  TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS ix_rag_chunks_source ON rag_chunks (source);
CREATE INDEX IF NOT EXISTS ix_rag_chunks_created ON rag_chunks (created_at DESC);

-- 向量近鄰索引 (超過 100 筆後執行)
-- CREATE INDEX IF NOT EXISTS ix_rag_chunks_embedding
--   ON rag_chunks USING ivfflat (embedding vector_cosine_ops)
--   WITH (lists = 10);

COMMENT ON TABLE rag_chunks IS 'RAG 知識庫向量片段 — Phase 28 ADR-067 (2026-04-10)';
