CREATE TABLE IF NOT EXISTS chat_session (
    id               BIGINT AUTO_INCREMENT PRIMARY KEY,
    user_id          BIGINT NOT NULL,
    session_uuid     CHAR(36) NOT NULL,              -- 可用于对外展示的ID（UUID）
    end_time         DATETIME NULL,
    status           VARCHAR(16) NOT NULL DEFAULT 'OPEN', -- OPEN/CLOSED/ABANDONED
    last_turn_id     BIGINT NULL,                    -- 指向 chat_turn.id
    ext_context      JSON NULL,                      -- 业务上下文
    created_at       DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at       DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE KEY uk_session_uuid (session_uuid),
    KEY idx_user_time (user_id, created_at),
    KEY idx_status_time (status, created_at),
    KEY idx_last_turn (last_turn_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS chat_turn (
    id                BIGINT AUTO_INCREMENT,
    session_id        BIGINT NOT NULL,                   -- 关联 chat_session.id
    turn_no           INT NOT NULL,                      -- 会话内轮次序号（1,2,3...）
    user_id           BIGINT NOT NULL,

    user_query        TEXT NOT NULL,                     -- 原始用户问句
    intent            VARCHAR(64) NULL,                  -- METRIC_QUERY/METRIC_EXPLAIN 等
    ast_json          JSON NULL,                         -- 解析出来的 AST

    generated_sql     MEDIUMTEXT NULL,                   -- 生成的最终SQL
    sql_status        VARCHAR(32) NULL,                  -- SUCCESS/FAILED/SKIPPED
    error_msg         TEXT NULL,                         -- SQL生成/执行错误信息

    main_metric_ids       JSON NULL,                     -- 本轮涉及的指标ID列表
    created_metric_ids    JSON NULL,                     -- 本轮新建指标ID列表

    end_time          DATETIME NULL,

    created_at        DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at        DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    -- 主键改为联合主键，必须包含 created_at
    PRIMARY KEY (id, created_at),
    KEY idx_session_turn (session_id, turn_no),
    KEY idx_session_time (session_id, created_at),
    KEY idx_intent_time (intent, created_at),
    KEY idx_user_time (user_id, created_at)
)
ENGINE=InnoDB
DEFAULT CHARSET=utf8mb4
PARTITION BY RANGE COLUMNS(created_at) (
    -- 历史数据分区（根据实际需求调整）
    PARTITION p202511 VALUES LESS THAN ('2025-12-01'),
    PARTITION p202512 VALUES LESS THAN ('2026-01-01'),
    -- 2026年按月分区
    PARTITION p202601 VALUES LESS THAN ('2026-02-01'),
    PARTITION p202602 VALUES LESS THAN ('2026-03-01'),
    PARTITION p202603 VALUES LESS THAN ('2026-04-01'),
    PARTITION p202604 VALUES LESS THAN ('2026-05-01'),
    PARTITION p202605 VALUES LESS THAN ('2026-06-01'),
    PARTITION p202606 VALUES LESS THAN ('2026-07-01'),
    -- ... 可以预建几个月 ...
    
    -- 兜底分区，存放未来的数据，防止插入报错
    PARTITION p_future VALUES LESS THAN (MAXVALUE)
);


CREATE TABLE IF NOT EXISTS chat_turn_retrieval (
    id                BIGINT AUTO_INCREMENT,
    turn_id           BIGINT NOT NULL,                 -- 关联 qa_turn.id

    item_type         VARCHAR(32) NOT NULL,            -- METRIC/SNIPPET/CHAT
    item_id           VARCHAR(128) NOT NULL,           -- metric_id/snippet_id/table_name 等
    item_extra        JSON NULL,                       -- 附加信息，如字段名等

    similarity_score  DECIMAL(10,6) NULL,              -- 相似度
    rank_no           INT NULL,                        -- 检索排名
    used_in_reasoning TINYINT(1) NOT NULL DEFAULT 0,   -- 是否参与推理
    used_in_sql       TINYINT(1) NOT NULL DEFAULT 0,   -- 是否影响最终SQL

    created_at        DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at        DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    -- 主键改为联合主键，必须包含 created_at
    PRIMARY KEY (id, created_at),
    KEY idx_turn (turn_id),
    KEY idx_turn_type (turn_id, item_type),
    KEY idx_item (item_type, item_id)
)
ENGINE=InnoDB
DEFAULT CHARSET=utf8mb4
PARTITION BY RANGE COLUMNS(created_at) (
    -- 历史数据分区（根据实际需求调整）
    PARTITION p202511 VALUES LESS THAN ('2025-12-01'),
    PARTITION p202512 VALUES LESS THAN ('2026-01-01'),
    -- 2026年按月分区
    PARTITION p202601 VALUES LESS THAN ('2026-02-01'),
    PARTITION p202602 VALUES LESS THAN ('2026-03-01'),
    PARTITION p202603 VALUES LESS THAN ('2026-04-01'),
    PARTITION p202604 VALUES LESS THAN ('2026-05-01'),
    PARTITION p202605 VALUES LESS THAN ('2026-06-01'),
    PARTITION p202606 VALUES LESS THAN ('2026-07-01'),
    -- ... 可以预建几个月 ...
    
    -- 兜底分区，存放未来的数据，防止插入报错
    PARTITION p_future VALUES LESS THAN (MAXVALUE)
);