-- ============================================================================
-- WeCom Middleware 数据库初始化脚本
-- 版本: 1.0.0
-- 作者: WeCom Middleware Team
-- 创建时间: 2026-03-08
-- ============================================================================

-- 创建数据库
CREATE DATABASE IF NOT EXISTS `wecom_middleware` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
USE `wecom_middleware`;

-- ============================================================================
-- 用户表
-- ============================================================================
CREATE TABLE IF NOT EXISTS `sys_user` (
  `id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `wecom_user_id` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '企业微信用户ID',
  `wecom_user_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '企业微信用户名称',
  `wecom_department_id` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '企业微信部门ID',
  `wecom_department_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '企业微信部门名称',
  `openclaw_session_id` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT 'OpenClaw会话ID',
  `status` tinyint NOT NULL DEFAULT '1' COMMENT '用户状态：0-禁用, 1-启用, 2-待验证',
  `role` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'user' COMMENT '用户角色：admin-管理员, user-普通用户, guest-访客',
  `last_login_time` datetime DEFAULT NULL COMMENT '最后登录时间',
  `last_active_time` datetime DEFAULT NULL COMMENT '最后活跃时间',
  `config` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci COMMENT '用户配置（JSON格式）',
  `remark` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '备注',
  `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  `create_by` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT 'system' COMMENT '创建人',
  `update_by` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT 'system' COMMENT '更新人',
  `deleted` tinyint NOT NULL DEFAULT '0' COMMENT '逻辑删除：0-未删除, 1-已删除',
  `version` int NOT NULL DEFAULT '0' COMMENT '版本号（乐观锁）',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_wecom_user_id` (`wecom_user_id`),
  KEY `idx_openclaw_session_id` (`openclaw_session_id`),
  KEY `idx_status` (`status`),
  KEY `idx_role` (`role`),
  KEY `idx_last_active_time` (`last_active_time`),
  KEY `idx_create_time` (`create_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='用户表';

-- ============================================================================
-- 会话表
-- ============================================================================
CREATE TABLE IF NOT EXISTS `sys_session` (
  `id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `user_id` bigint NOT NULL COMMENT '用户ID',
  `wecom_session_id` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '企业微信会话ID',
  `openclaw_session_id` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT 'OpenClaw会话ID',
  `status` tinyint NOT NULL DEFAULT '1' COMMENT '会话状态：0-已断开, 1-连接中, 2-等待响应, 3-错误',
  `type` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'direct' COMMENT '会话类型：direct-私聊, group-群聊, system-系统',
  `wecom_chat_id` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '企业微信聊天ID',
  `wecom_chat_type` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '企业微信聊天类型：single-单聊, group-群聊',
  `openclaw_session_key` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT 'OpenClaw会话Key',
  `last_message_time` datetime DEFAULT NULL COMMENT '最后消息时间',
  `message_count` int NOT NULL DEFAULT '0' COMMENT '消息计数',
  `config` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci COMMENT '会话配置（JSON格式）',
  `error_info` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci COMMENT '错误信息',
  `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  `expire_time` datetime DEFAULT NULL COMMENT '过期时间',
  `deleted` tinyint NOT NULL DEFAULT '0' COMMENT '逻辑删除：0-未删除, 1-已删除',
  `version` int NOT NULL DEFAULT '0' COMMENT '版本号（乐观锁）',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_session_key` (`wecom_session_id`, `openclaw_session_id`),
  KEY `idx_user_id` (`user_id`),
  KEY `idx_wecom_session_id` (`wecom_session_id`),
  KEY `idx_openclaw_session_id` (`openclaw_session_id`),
  KEY `idx_status` (`status`),
  KEY `idx_type` (`type`),
  KEY `idx_last_message_time` (`last_message_time`),
  KEY `idx_create_time` (`create_time`),
  KEY `idx_expire_time` (`expire_time`),
  CONSTRAINT `fk_session_user` FOREIGN KEY (`user_id`) REFERENCES `sys_user` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='会话表';

-- ============================================================================
-- 消息表
-- ============================================================================
CREATE TABLE IF NOT EXISTS `sys_message` (
  `id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `session_id` bigint NOT NULL COMMENT '会话ID',
  `direction` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '消息方向：wecom_to_openclaw-企业微信到OpenClaw, openclaw_to_wecom-OpenClaw到企业微信, system-系统消息',
  `message_type` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '消息类型：text-文本, image-图片, file-文件, voice-语音, video-视频, mixed-混合, system-系统',
  `content` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci COMMENT '消息内容',
  `raw_content` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci COMMENT '原始消息内容（JSON格式）',
  `media_url` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '媒体文件URL',
  `media_local_path` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '媒体文件本地路径',
  `media_type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '媒体文件类型',
  `media_size` bigint DEFAULT NULL COMMENT '媒体文件大小（字节）',
  `status` tinyint NOT NULL DEFAULT '0' COMMENT '消息状态：0-发送中, 1-已发送, 2-已接收, 3-已读, 4-失败, 5-超时',
  `wecom_message_id` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '企业微信消息ID',
  `openclaw_message_id` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT 'OpenClaw消息ID',
  `sequence` bigint DEFAULT NULL COMMENT '消息序列号',
  `is_quote` tinyint NOT NULL DEFAULT '0' COMMENT '是否引用消息：0-否, 1-是',
  `quote_message_id` bigint DEFAULT NULL COMMENT '引用消息ID',
  `sender_id` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '发送者ID',
  `receiver_id` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '接收者ID',
  `send_time` datetime DEFAULT NULL COMMENT '发送时间',
  `receive_time` datetime DEFAULT NULL COMMENT '接收时间',
  `process_duration` bigint DEFAULT NULL COMMENT '处理耗时（毫秒）',
  `error_info` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci COMMENT '错误信息',
  `retry_count` int NOT NULL DEFAULT '0' COMMENT '重试次数',
  `tags` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '消息标签',
  `extras` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci COMMENT '扩展字段（JSON格式）',
  `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  `deleted` tinyint NOT NULL DEFAULT '0' COMMENT '逻辑删除：0-未删除, 1-已删除',
  `version` int NOT NULL DEFAULT '0' COMMENT '版本号（乐观锁）',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_wecom_message_id` (`wecom_message_id`),
  UNIQUE KEY `uk_openclaw_message_id` (`openclaw_message_id`),
  KEY `idx_session_id` (`session_id`),
  KEY `idx_direction` (`direction`),
  KEY `idx_message_type` (`message_type`),
  KEY `idx_status` (`status`),
  KEY `idx_send_time` (`send_time`),
  KEY `idx_receive_time` (`receive_time`),
  KEY `idx_create_time` (`create_time`),
  KEY `idx_sequence` (`sequence`),
  KEY `idx_sender_id` (`sender_id`),
  KEY `idx_receiver_id` (`receiver_id`),
  CONSTRAINT `fk_message_session` FOREIGN KEY (`session_id`) REFERENCES `sys_session` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='消息表';

-- ============================================================================
-- 系统配置表
-- ============================================================================
CREATE TABLE IF NOT EXISTS `sys_config` (
  `id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `config_key` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '配置键',
  `config_value` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci COMMENT '配置值',
  `config_type` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'string' COMMENT '配置类型：string-字符串, number-数字, boolean-布尔, json-JSON, yaml-YAML',
  `config_group` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '配置分组：wecom-企业微信, openclaw-OpenClaw, system-系统, security-安全, monitor-监控',
  `config_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '配置名称',
  `config_desc` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '配置描述',
  `editable` tinyint NOT NULL DEFAULT '1' COMMENT '是否可修改：0-只读, 1-可修改',
  `encrypted` tinyint NOT NULL DEFAULT '0' COMMENT '是否加密存储：0-明文, 1-加密',
  `config_version` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT '1.0.0' COMMENT '配置版本',
  `effective_time` datetime DEFAULT NULL COMMENT '生效时间',
  `expire_time` datetime DEFAULT NULL COMMENT '过期时间',
  `sort_order` int NOT NULL DEFAULT '0' COMMENT '排序号',
  `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  `create_by` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT 'system' COMMENT '创建人',
  `update_by` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT 'system' COMMENT '更新人',
  `deleted` tinyint NOT NULL DEFAULT '0' COMMENT '逻辑删除：0-未删除, 1-已删除',
  `version` int NOT NULL DEFAULT '0' COMMENT '版本号（乐观锁）',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_config_key_group` (`config_key`, `config_group`),
  KEY `idx_config_group` (`config_group`),
  KEY `idx_editable` (`editable`),
  KEY `idx_sort_order` (`sort_order`),
  KEY `idx_effective_time` (`effective_time`),
  KEY `idx_expire_time` (`expire_time`),
  KEY `idx_create_time` (`create_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='系统配置表';

-- ============================================================================
-- 操作日志表
-- ============================================================================
CREATE TABLE IF NOT EXISTS `sys_operation_log` (
  `id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `user_id` bigint DEFAULT NULL COMMENT '用户ID',
  `operation_type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '操作类型',
  `operation_module` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '操作模块',
  `operation_content` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci COMMENT '操作内容',
  `request_method` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '请求方法',
  `request_url` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '请求URL',
  `request_params` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci COMMENT '请求参数',
  `response_result` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci COMMENT '响应结果',
  `ip_address` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT 'IP地址',
  `user_agent` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '用户代理',
  `status` tinyint NOT NULL DEFAULT '1' COMMENT '操作状态：0-失败, 1-成功',
  `error_message` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci COMMENT '错误信息',
  `execute_time` bigint DEFAULT NULL COMMENT '执行时间（毫秒）',
  `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  PRIMARY KEY (`id`),
  KEY `idx_user_id` (`user_id`),
  KEY `idx_operation_type` (`operation_type`),
  KEY `idx_operation_module` (`operation_module`),
  KEY `idx_status` (`status`),
  KEY `idx_create_time` (`create_time`),
  KEY `idx_ip_address` (`ip_address`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='操作日志表';

-- ============================================================================
-- 连接状态表
-- ============================================================================
CREATE TABLE IF NOT EXISTS `sys_connection_status` (
  `id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `connection_type` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '连接类型：wecom-企业微信, openclaw-OpenClaw',
  `connection_id` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '连接ID',
  `status` tinyint NOT NULL DEFAULT '0' COMMENT '连接状态：0-断开, 1-连接中, 2-重连中, 3-错误',
  `last_connect_time` datetime DEFAULT NULL COMMENT '最后连接时间',
  `last_disconnect_time` datetime DEFAULT NULL COMMENT '最后断开时间',
  `connect_count` int NOT NULL DEFAULT '0' COMMENT '连接次数',
  `disconnect_count` int NOT NULL DEFAULT '0' COMMENT '断开次数',
  `error_count` int NOT NULL DEFAULT '0' COMMENT '错误次数',
  `last_error_message` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci COMMENT '最后错误信息',
  `heartbeat_time` datetime DEFAULT NULL COMMENT '心跳时间',
  `config` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci COMMENT '连接配置（JSON格式）',
  `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_connection_type` (`connection_type`),
  KEY `idx_status` (`status`),
  KEY `idx_last_connect_time` (`last_connect_time`),
  KEY `idx_heartbeat_time` (`heartbeat_time`),
  KEY `idx_create_time` (`create_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='连接状态表';

-- ============================================================================
-- 企业微信Bot配置表
-- ============================================================================
CREATE TABLE IF NOT EXISTS `bot_config` (
  `id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `bot_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT 'Bot名称',
  `wecom_bot_id` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '企业微信Bot ID',
  `wecom_bot_secret` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '企业微信Bot Secret',
  `wecom_websocket_url` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT 'wss://openws.work.weixin.qq.com' COMMENT '企业微信WebSocket URL',
  `openclaw_agent_id` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT 'OpenClaw代理Agent ID',
  `openclaw_gateway_url` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT 'ws://localhost:18789' COMMENT 'OpenClaw网关URL',
  `openclaw_gateway_token` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT 'OpenClaw网关Token',
  `client_id` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT 'wecom-middleware' COMMENT '客户端ID',
  `device_id` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT 'wecom-device' COMMENT '设备ID',
  `protocol_version` int DEFAULT '3' COMMENT '协议版本',
  `status` tinyint NOT NULL DEFAULT '1' COMMENT 'Bot状态：0-禁用，1-启用，2-连接中，3-已连接，4-错误',
  `last_connect_time` datetime DEFAULT NULL COMMENT '最后连接时间',
  `last_disconnect_time` datetime DEFAULT NULL COMMENT '最后断开时间',
  `error_message` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci COMMENT '错误信息',
  `heartbeat_interval` int DEFAULT '30000' COMMENT '心跳间隔（毫秒）',
  `reconnect_interval` int DEFAULT '5000' COMMENT '重连间隔（毫秒）',
  `max_retry_count` int DEFAULT '3' COMMENT '最大重试次数',
  `message_queue_size` int DEFAULT '1000' COMMENT '消息队列大小',
  `config_json` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci COMMENT '配置JSON',
  `description` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '描述信息',
  `dm_policy` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT 'pairing' COMMENT '配对策略：pairing-需要配对批准，allowlist-仅允许列表中的用户，open-开放所有用户，disabled-禁用配对',
  `allow_from` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci COMMENT '允许的用户列表（JSON数组格式）',
  `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  `create_by` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT 'system' COMMENT '创建人',
  `update_by` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT 'system' COMMENT '更新人',
  `deleted` tinyint NOT NULL DEFAULT '0' COMMENT '逻辑删除：0-未删除，1-已删除',
  `version` int NOT NULL DEFAULT '0' COMMENT '版本号（乐观锁）',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_wecom_bot_id` (`wecom_bot_id`),
  UNIQUE KEY `uk_openclaw_agent_id` (`openclaw_agent_id`),
  KEY `idx_status` (`status`),
  KEY `idx_bot_name` (`bot_name`),
  KEY `idx_last_connect_time` (`last_connect_time`),
  KEY `idx_create_time` (`create_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='企业微信Bot配置表';

-- ============================================================================
-- OpenClaw配对请求表
-- ============================================================================
CREATE TABLE IF NOT EXISTS `pairing_request` (
  `id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `request_id` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '请求ID（OpenClaw生成的唯一ID）',
  `node_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '节点名称',
  `node_type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '节点类型',
  `node_description` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci COMMENT '节点描述',
  `node_version` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '节点版本',
  `operating_system` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '操作系统',
  `hostname` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '主机名',
  `ip_address` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT 'IP地址',
  `request_time` datetime DEFAULT NULL COMMENT '请求时间',
  `expire_time` datetime DEFAULT NULL COMMENT '过期时间',
  `status` tinyint NOT NULL DEFAULT '0' COMMENT '状态：0-待处理，1-已批准，2-已拒绝，3-已过期',
  `approver` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '审批人',
  `approve_time` datetime DEFAULT NULL COMMENT '审批时间',
  `reject_reason` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci COMMENT '拒绝原因',
  `auto_approve` tinyint DEFAULT '0' COMMENT '自动审批：0-手动，1-自动',
  `approve_rule_id` bigint DEFAULT NULL COMMENT '审批规则ID',
  `bot_id` bigint DEFAULT NULL COMMENT '关联的Bot ID',
  `remark` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '备注',
  `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  `deleted` tinyint NOT NULL DEFAULT '0' COMMENT '逻辑删除：0-未删除，1-已删除',
  `version` int NOT NULL DEFAULT '0' COMMENT '版本号（乐观锁）',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_request_id` (`request_id`),
  KEY `idx_status` (`status`),
  KEY `idx_node_name` (`node_name`),
  KEY `idx_hostname` (`hostname`),
  KEY `idx_ip_address` (`ip_address`),
  KEY `idx_request_time` (`request_time`),
  KEY `idx_expire_time` (`expire_time`),
  KEY `idx_approve_time` (`approve_time`),
  KEY `idx_bot_id` (`bot_id`),
  KEY `idx_create_time` (`create_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='OpenClaw配对请求表';

-- ============================================================================
-- 初始化数据
-- ============================================================================

-- 插入默认管理员用户
INSERT INTO `sys_user` (
  `wecom_user_id`, `wecom_user_name`, `status`, `role`, `config`, `remark`, `create_by`, `update_by`
) VALUES (
  'admin', '系统管理员', 1, 'admin', 
  '{"theme":"light","language":"zh-CN","notification":true}',
  '系统默认管理员账户',
  'system', 'system'
) ON DUPLICATE KEY UPDATE `update_time` = CURRENT_TIMESTAMP;

-- 插入系统默认配置
INSERT INTO `sys_config` (
  `config_key`, `config_value`, `config_type`, `config_group`, `config_name`, `config_desc`, `editable`, `sort_order`
) VALUES
-- 企业微信配置
('bot.id', '', 'string', 'wecom', '企业微信机器人ID', '企业微信智能机器人的Bot ID', 1, 10),
('bot.secret', '', 'string', 'wecom', '企业微信机器人密钥', '企业微信智能机器人的Secret', 1, 20),
('websocket.url', 'wss://openws.work.weixin.qq.com', 'string', 'wecom', 'WebSocket连接地址', '企业微信WebSocket服务器地址', 0, 30),
('reconnect.max.attempts', '100', 'number', 'wecom', '最大重连次数', 'WebSocket连接断开后的最大重连次数', 1, 40),
('heartbeat.interval.ms', '30000', 'number', 'wecom', '心跳间隔(毫秒)', '发送心跳包的时间间隔', 1, 50),

-- OpenClaw配置
('gateway.url', 'ws://localhost:18789', 'string', 'openclaw', 'OpenClaw网关地址', 'OpenClaw网关WebSocket地址', 1, 60),
('gateway.token', '', 'string', 'openclaw', 'OpenClaw网关令牌', '连接OpenClaw网关的认证令牌', 1, 70),
('protocol.version', '3', 'number', 'openclaw', '协议版本', 'OpenClaw WebSocket协议版本', 0, 80),
('client.id', 'wecom-middleware', 'string', 'openclaw', '客户端ID', '连接OpenClaw的客户端标识', 0, 90),
('client.role', 'operator', 'string', 'openclaw', '客户端角色', '连接OpenClaw的客户端角色', 0, 100),

-- 系统配置
('session.timeout.minutes', '30', 'number', 'system', '会话超时时间(分钟)', '用户会话的超时时间', 1, 110),
('message.retry.max.count', '3', 'number', 'system', '消息最大重试次数', '消息发送失败后的最大重试次数', 1, 120),
('message.save.days', '30', 'number', 'system', '消息保存天数', '消息历史记录的保存天数', 1, 130),
('log.retention.days', '90', 'number', 'system', '日志保留天数', '操作日志的保留天数', 1, 140),
('monitor.enabled', 'true', 'boolean', 'system', '启用监控', '是否启用系统监控', 1, 150),

-- 安全配置
('jwt.secret', 'wecom-middleware-secret-key-change-in-production', 'string', 'security', 'JWT密钥', 'JWT令牌签名密钥，生产环境必须修改', 1, 160),
('jwt.expiration.hours', '24', 'number', 'security', 'JWT过期时间(小时)', 'JWT令牌的有效期', 1, 170),
('cors.allowed.origins', '*', 'string', 'security', 'CORS允许来源', '跨域资源共享允许的来源', 1, 180),
('rate.limit.enabled', 'true', 'boolean', 'security', '启用限流', '是否启用API限流', 1, 190),
('rate.limit.max.requests', '1000', 'number', 'security', '最大请求数', '每分钟最大请求数', 1, 200),

-- 监控配置
('monitor.interval.seconds', '60', 'number', 'monitor', '监控间隔(秒)', '系统监控数据采集间隔', 1, 210),
('metrics.export.enabled', 'true', 'boolean', 'monitor', '启用指标导出', '是否启用监控指标导出', 1, 220),
('health.check.enabled', 'true', 'boolean', 'monitor', '启用健康检查', '是否启用系统健康检查', 1, 230),
('alert.enabled', 'false', 'boolean', 'monitor', '启用告警', '是否启用系统告警', 1, 240),
('alert.threshold.cpu', '80', 'number', 'monitor', 'CPU告警阈值(%)', 'CPU使用率告警阈值', 1, 250)
ON DUPLICATE KEY UPDATE `update_time` = CURRENT_TIMESTAMP, `config_version` = '1.0.0';

-- 插入初始连接状态
INSERT INTO `sys_connection_status` (
  `connection_type`, `status`, `connect_count`, `disconnect_count`, `config`
) VALUES
('wecom', 0, 0, 0, '{"type":"wecom","description":"企业微信智能机器人连接"}'),
('openclaw', 0, 0, 0, '{"type":"openclaw","description":"OpenClaw网关连接"}')
ON DUPLICATE KEY UPDATE `update_time` = CURRENT_TIMESTAMP;

-- ============================================================================
-- 创建视图
-- ============================================================================

-- 用户会话视图
CREATE OR REPLACE VIEW `v_user_session` AS
SELECT 
  u.id AS user_id,
  u.wecom_user_id,
  u.wecom_user_name,
  u.role,
  u.status AS user_status,
  u.last_active_time,
  s.id AS session_id,
  s.wecom_session_id,
  s.openclaw_session_id,
  s.status AS session_status,
  s.type AS session_type,
  s.last_message_time,
  s.message_count,
  s.create_time AS session_create_time
FROM sys_user u
LEFT JOIN sys_session s ON u.id = s.user_id AND s.deleted = 0 AND s.status = 1
WHERE u.deleted = 0;

-- 消息统计视图
CREATE OR REPLACE VIEW `v_message_statistics` AS
SELECT 
  DATE(create_time) AS stat_date,
  direction,
  message_type,
  COUNT(*) AS message_count,
  SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) AS success_count,
  SUM(CASE WHEN status = 4 THEN 1 ELSE 0 END) AS failure_count,
  AVG(process_duration) AS avg_process_duration
FROM sys_message
WHERE deleted = 0
GROUP BY DATE(create_time), direction, message_type;

-- 连接状态视图
CREATE OR REPLACE VIEW `v_connection_status` AS
SELECT 
  connection_type,
  status,
  last_connect_time,
  last_disconnect_time,
  connect_count,
  disconnect_count,
  error_count,
  TIMESTAMPDIFF(SECOND, last_connect_time, NOW()) AS connected_seconds,
  CASE 
    WHEN status = 1 THEN '连接正常'
    WHEN status = 0 THEN '已断开'
    WHEN status = 2 THEN '重连中'
    WHEN status = 3 THEN '连接错误'
    ELSE '未知状态'
  END AS status_description
FROM sys_connection_status;

-- ============================================================================
-- 创建存储过程
-- ============================================================================

-- 清理过期会话的存储过程
DELIMITER //
CREATE PROCEDURE `sp_cleanup_expired_sessions`()
BEGIN
  -- 标记过期会话为断开状态
  UPDATE sys_session 
  SET status = 0, update_time = NOW(), error_info = '会话已过期'
  WHERE status = 1 AND expire_time IS NOT NULL AND expire_time < NOW();
  
  -- 清理长时间未活动的会话（超过7天）
  UPDATE sys_session 
  SET status = 0, update_time = NOW(), error_info = '会话长时间未活动'
  WHERE status = 1 AND last_message_time IS NOT NULL AND last_message_time < DATE_SUB(NOW(), INTERVAL 7 DAY);
  
  SELECT ROW_COUNT() AS cleaned_sessions;
END //
DELIMITER ;

-- 消息重试的存储过程
DELIMITER //
CREATE PROCEDURE `sp_retry_failed_messages`()
BEGIN
  -- 更新需要重试的消息状态
  UPDATE sys_message 
  SET status = 0, retry_count = retry_count + 1, update_time = NOW()
  WHERE status = 4 AND retry_count < 3 AND create_time > DATE_SUB(NOW(), INTERVAL 1 HOUR);
  
  SELECT ROW_COUNT() AS retry_messages;
END //
DELIMITER ;

-- ============================================================================
-- 创建事件调度
-- ============================================================================

-- 启用事件调度器
SET GLOBAL event_scheduler = ON;

-- 每天凌晨清理过期数据
CREATE EVENT IF NOT EXISTS `event_daily_cleanup`
ON SCHEDULE EVERY 1 DAY STARTS '2026-03-09 03:00:00'
DO
BEGIN
  -- 清理过期会话
  CALL sp_cleanup_expired_sessions();
  
  -- 清理30天前的消息（根据配置可调整）
  DELETE FROM sys_message 
  WHERE deleted = 0 AND create_time < DATE_SUB(NOW(), INTERVAL 30 DAY);
  
  -- 清理90天前的操作日志
  DELETE FROM sys_operation_log 
  WHERE create_time < DATE_SUB(NOW(), INTERVAL 90 DAY);
END;

-- 每小时检查并重试失败消息
CREATE EVENT IF NOT EXISTS `event_hourly_message_retry`
ON SCHEDULE EVERY 1 HOUR STARTS '2026-03-09 00:05:00'
DO
BEGIN
  CALL sp_retry_failed_messages();
END;

-- ============================================================================
-- 创建函数
-- ============================================================================

-- 获取配置值的函数
DELIMITER //
CREATE FUNCTION `fn_get_config`(p_config_key VARCHAR(100), p_config_group VARCHAR(50))
RETURNS TEXT
DETERMINISTIC
READS SQL DATA
BEGIN
  DECLARE v_config_value TEXT;
  
  SELECT config_value INTO v_config_value
  FROM sys_config
  WHERE config_key = p_config_key 
    AND config_group = p_config_group
    AND deleted = 0
    AND (effective_time IS NULL OR effective_time <= NOW())
    AND (expire_time IS NULL OR expire_time > NOW())
  ORDER BY config_version DESC, update_time DESC
  LIMIT 1;
  
  RETURN v_config_value;
END //
DELIMITER ;

-- ============================================================================
-- 完成提示
-- ============================================================================
SELECT '数据库初始化完成！' AS message;

-- 显示表结构信息
SELECT 
  TABLE_NAME,
  TABLE_COMMENT,
  TABLE_ROWS,
  DATA_LENGTH,
  INDEX_LENGTH,
  CREATE_TIME
FROM information_schema.TABLES 
WHERE TABLE_SCHEMA = 'wecom_middleware'
ORDER BY TABLE_NAME;