CREATE TABLE IF NOT EXISTS chat_sessions (
    id BIGSERIAL PRIMARY KEY,
    user_id BIGINT NOT NULL,
    title TEXT NOT NULL DEFAULT '新对话',
    summary TEXT DEFAULT '',
    memory_json TEXT NOT NULL DEFAULT '{}',
    last_symbol TEXT DEFAULT '',
    last_intent TEXT DEFAULT '',
    created_at TEXT NOT NULL,
    updated_at TEXT NOT NULL,
    archived_at TEXT DEFAULT ''
);
CREATE INDEX IF NOT EXISTS idx_chat_sessions_user_updated ON chat_sessions(user_id, updated_at DESC);

CREATE TABLE IF NOT EXISTS chat_messages (
    id BIGSERIAL PRIMARY KEY,
    session_id BIGINT NOT NULL,
    user_id BIGINT NOT NULL,
    role TEXT NOT NULL,
    content_text TEXT DEFAULT '',
    content_json TEXT NOT NULL DEFAULT '{}',
    context_json TEXT NOT NULL DEFAULT '{}',
    intent TEXT DEFAULT '',
    symbol TEXT DEFAULT '',
    timeframe TEXT DEFAULT '',
    model TEXT DEFAULT '',
    created_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_chat_messages_session_time ON chat_messages(session_id, created_at ASC);
CREATE INDEX IF NOT EXISTS idx_chat_messages_user_time ON chat_messages(user_id, created_at DESC);

CREATE TABLE IF NOT EXISTS chat_user_preferences (
    user_id BIGINT PRIMARY KEY,
    preferences_json TEXT NOT NULL DEFAULT '{}',
    updated_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_chat_user_preferences_updated ON chat_user_preferences(updated_at DESC);
