-- AI Chat Service 数据库迁移
-- 创建时间: 2026-05-27
-- 说明: AI Chat Service 所需的数据库表

-- =============================================
-- 1. ai_personas (人设表)
-- =============================================
CREATE TABLE IF NOT EXISTS ai_personas (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id BIGINT NOT NULL,
    name VARCHAR(64) NOT NULL,
    description TEXT,
    avatar_url VARCHAR(512),
    talk_style VARCHAR(256),
    system_prompt TEXT NOT NULL,
    is_default BOOLEAN DEFAULT FALSE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- 索引
CREATE INDEX IF NOT EXISTS idx_ai_personas_user_id ON ai_personas(user_id);
CREATE UNIQUE INDEX IF NOT EXISTS idx_ai_personas_user_default ON ai_personas(user_id) WHERE is_default = TRUE;

-- =============================================
-- 2. ai_user_memories (长期记忆表)
-- =============================================
CREATE TABLE IF NOT EXISTS ai_user_memories (
    id SERIAL PRIMARY KEY,
    user_id BIGINT NOT NULL,
    content TEXT NOT NULL,
    keywords TEXT[],
    weight INTEGER DEFAULT 50,
    is_core BOOLEAN DEFAULT FALSE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- 索引
CREATE INDEX IF NOT EXISTS idx_ai_user_memories_user_id ON ai_user_memories(user_id);
CREATE INDEX IF NOT EXISTS idx_ai_user_memories_keywords ON ai_user_memories USING GIN(keywords);
CREATE INDEX IF NOT EXISTS idx_ai_user_memories_weight ON ai_user_memories(weight DESC);

-- =============================================
-- 3. ai_chat_configs (配置表，存储 Dify/LLM 等配置)
-- =============================================
CREATE TABLE IF NOT EXISTS ai_chat_configs (
    id SERIAL PRIMARY KEY,
    config_key VARCHAR(128) UNIQUE NOT NULL,
    config_value TEXT NOT NULL,
    config_type VARCHAR(32) DEFAULT 'string',
    category VARCHAR(64),
    description VARCHAR(256),
    is_encrypted BOOLEAN DEFAULT FALSE,
    updated_at BIGINT,
    created_at BIGINT
);

-- 索引
CREATE INDEX IF NOT EXISTS idx_ai_chat_configs_category ON ai_chat_configs(category);

-- =============================================
-- 回滚语句 (如需回滚)
-- =============================================
-- DROP TABLE IF EXISTS ai_chat_configs;
-- DROP TABLE IF EXISTS ai_user_memories;
-- DROP TABLE IF EXISTS ai_personas;