-- 消息表
CREATE TABLE IF NOT EXISTS messages (
    id          BIGSERIAL PRIMARY KEY,
    session_id  UUID NOT NULL,
    role        VARCHAR(10) NOT NULL,
    content     TEXT NOT NULL,
    tokens_used INTEGER NOT NULL DEFAULT 0,
    created_at  TIMESTAMPTZ NOT NULL DEFAULT NOW(),

    CONSTRAINT check_tokens_non_negative CHECK (tokens_used >= 0)
);

-- 按会话查询消息（分页核心索引）
CREATE INDEX IF NOT EXISTS idx_messages_session_id_created_at
    ON messages(session_id, created_at);

-- 按会话查询最后一条消息
CREATE INDEX IF NOT EXISTS idx_messages_session_id_id_desc
    ON messages(session_id, id DESC);

-- 表和列注释
COMMENT ON TABLE messages IS '消息表，存储所有会话的消息记录';
COMMENT ON COLUMN messages.id IS '消息唯一标识符，自增序列';
COMMENT ON COLUMN messages.session_id IS '所属会话 ID，关联 sessions 表';
COMMENT ON COLUMN messages.role IS '消息角色，可选值: ''user'' (用户), ''assistant'' (AI 助手), ''system'' (系统)';
COMMENT ON COLUMN messages.content IS '消息内容，无长度限制';
COMMENT ON COLUMN messages.tokens_used IS '消息消耗的 token 数量，用于计费统计';
COMMENT ON COLUMN messages.created_at IS '消息创建时间';
