CREATE TABLE IF NOT EXISTS mci_flow_definition (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    tenant_code VARCHAR(64) NOT NULL COMMENT '所属租户',
    flow_code VARCHAR(64) NOT NULL COMMENT '流程编码',
    flow_name VARCHAR(128) NOT NULL COMMENT '流程名称',
    flow_type VARCHAR(32) NOT NULL COMMENT '流程类型：inbound / ivr',
    definition_json JSON NOT NULL COMMENT '流程定义 JSON',
    status TINYINT NOT NULL DEFAULT 0 COMMENT '状态：0下线 1上线',
    create_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    update_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    deleted TINYINT NOT NULL DEFAULT 0,
    UNIQUE KEY uk_tenant_flow_code (tenant_code, flow_code, deleted)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='流程定义表';

CREATE TABLE IF NOT EXISTS mci_message_event (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    event_id VARCHAR(128) NOT NULL COMMENT '事件唯一 ID',
    tenant_code VARCHAR(64) NOT NULL COMMENT '所属租户/业务系统',
    channel_type VARCHAR(32) NOT NULL COMMENT '渠道',
    channel_subject_id BIGINT COMMENT '渠道主体',
    direction TINYINT NOT NULL DEFAULT 1 COMMENT '方向：1入站 2出站',
    event_type VARCHAR(32) NOT NULL COMMENT '事件类型：message / callback / status / keypress',
    message_source VARCHAR(32) NOT NULL COMMENT '来源：realtime / session_archive',
    conversation_id BIGINT COMMENT '会话 ID',
    person_id BIGINT COMMENT '联系人 ID',
    account_id BIGINT COMMENT '发送/接收账号',
    content JSON COMMENT '内容：{type, body}',
    raw_payload JSON COMMENT '渠道原始报文',
    business_context JSON COMMENT '业务上下文',
    is_processed TINYINT NOT NULL DEFAULT 0 COMMENT '是否已处理：0否 1是',
    status TINYINT NOT NULL DEFAULT 1 COMMENT '状态',
    create_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    update_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    deleted TINYINT NOT NULL DEFAULT 0,
    UNIQUE KEY uk_event_id (event_id),
    KEY idx_tenant_source_time (tenant_code, message_source, create_time),
    KEY idx_conversation_time (conversation_id, create_time),
    KEY idx_person_time (person_id, create_time),
    KEY idx_account_time (account_id, create_time)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='消息事件表';
