-- Chat Switchboard — 008 Memory (SQLite)
-- Consolidated v0.28.0: adds last_compacted_at + decay_rate

CREATE TABLE IF NOT EXISTS memories (
    id                TEXT PRIMARY KEY,
    scope             TEXT NOT NULL CHECK (scope IN ('user', 'persona', 'persona_user')),
    owner_id          TEXT NOT NULL,
    user_id           TEXT,
    key               TEXT NOT NULL,
    value             TEXT NOT NULL,
    source_channel_id TEXT,
    confidence        REAL NOT NULL DEFAULT 1.0,
    status            TEXT NOT NULL DEFAULT 'active'
                      CHECK (status IN ('active', 'pending_review', 'archived')),
    embedding         TEXT,
    last_compacted_at TEXT,
    decay_rate        REAL NOT NULL DEFAULT 0.0,
    created_at        TEXT DEFAULT (datetime('now')),
    updated_at        TEXT DEFAULT (datetime('now'))
);

CREATE INDEX IF NOT EXISTS idx_memories_scope_owner
    ON memories(scope, owner_id, status);

CREATE INDEX IF NOT EXISTS idx_memories_persona_user
    ON memories(owner_id, user_id);

CREATE UNIQUE INDEX IF NOT EXISTS idx_memories_unique_key
    ON memories(scope, owner_id, COALESCE(user_id, '00000000-0000-0000-0000-000000000000'), key);

CREATE INDEX IF NOT EXISTS idx_memories_source_channel
    ON memories(source_channel_id);

CREATE TABLE IF NOT EXISTS memory_extraction_log (
    id            TEXT PRIMARY KEY,
    channel_id    TEXT NOT NULL,
    user_id       TEXT NOT NULL,
    last_message_id TEXT NOT NULL,
    extracted_at  TEXT DEFAULT (datetime('now')),
    memory_count  INTEGER NOT NULL DEFAULT 0,
    UNIQUE(channel_id, user_id)
);

CREATE INDEX IF NOT EXISTS idx_mem_extract_log_channel
    ON memory_extraction_log(channel_id);
