-- Petstore 智能预约助手 M0：短期会话、草稿版本和固定 TTL
-- 前置：20260802_create_follow_up_task.sql 已执行。
-- 本表不保存当轮原文、原始语音、提示词、模型响应或 Appointment 关联。

CREATE TABLE t_booking_agent_session (
    id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    session_id VARCHAR(36) NOT NULL,
    customer_user_id BIGINT NOT NULL,
    store_id BIGINT NOT NULL,
    status VARCHAR(24) NOT NULL COMMENT 'collecting | proposing | confirmable | fallback | expired | cancelled',
    draft_json TEXT NOT NULL,
    draft_version INT NOT NULL DEFAULT 0,
    entry_source VARCHAR(32) NOT NULL,
    input_modality VARCHAR(16) NULL COMMENT 'text | voice | mixed；首次成功消息后派生',
    expires_at DATETIME NOT NULL,
    create_time DATETIME NOT NULL,
    update_time DATETIME NOT NULL,
    CONSTRAINT uk_booking_agent_session_public_id UNIQUE (session_id),
    CONSTRAINT chk_booking_agent_session_status CHECK (
        status IN ('collecting', 'proposing', 'confirmable', 'fallback', 'expired', 'cancelled')
    ),
    CONSTRAINT chk_booking_agent_input_modality CHECK (
        input_modality IS NULL OR input_modality IN ('text', 'voice', 'mixed')
    ),
    INDEX idx_booking_agent_customer_status_expire (customer_user_id, status, expires_at),
    INDEX idx_booking_agent_status_expire (status, expires_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='智能预约 M0 短期结构化草稿会话';

-- 验证：以下四项在上线迁移完成且清理任务正常后必须全部为 0。
SELECT COUNT(*) AS invalid_booking_agent_state_count
FROM t_booking_agent_session
WHERE status NOT IN ('collecting', 'proposing', 'confirmable', 'fallback', 'expired', 'cancelled')
   OR draft_version < 0
   OR entry_source <> 'appointment_create'
   OR (input_modality IS NOT NULL AND input_modality NOT IN ('text', 'voice', 'mixed'));

SELECT COUNT(*) AS duplicate_booking_agent_public_id_count
FROM (
    SELECT session_id
    FROM t_booking_agent_session
    GROUP BY session_id
    HAVING COUNT(*) > 1
) duplicated;

SELECT COUNT(*) AS invalid_booking_agent_ttl_count
FROM t_booking_agent_session
WHERE expires_at <= create_time;

SELECT COUNT(*) AS stale_active_booking_agent_session_count
FROM t_booking_agent_session
WHERE status IN ('collecting', 'proposing', 'confirmable')
  AND expires_at <= NOW();
