CREATE TABLE IF NOT EXISTS sys_broadcast_message (
  id BIGINT PRIMARY KEY AUTO_INCREMENT COMMENT '主键ID',
  title VARCHAR(100) NOT NULL COMMENT '广播标题',
  content VARCHAR(500) NOT NULL COMMENT '广播内容',
  tone VARCHAR(32) NOT NULL DEFAULT 'INFO' COMMENT '提示类型：INFO/SUCCESS/WARNING/DANGER',
  status VARCHAR(32) NOT NULL DEFAULT 'ACTIVE' COMMENT '状态：ACTIVE/PAUSED',
  starts_at DATETIME NULL COMMENT '开始展示时间',
  ends_at DATETIME NULL COMMENT '结束展示时间',
  sort_no INT NOT NULL DEFAULT 0 COMMENT '排序号，越大越优先',
  created_by BIGINT NULL COMMENT '创建用户ID',
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  KEY idx_broadcast_status_time (status, starts_at, ends_at),
  CONSTRAINT fk_broadcast_created_by FOREIGN KEY (created_by) REFERENCES sys_user(id)
) ENGINE=InnoDB COMMENT='系统广播消息';

CREATE TABLE IF NOT EXISTS sys_ai_assistant_config (
  id BIGINT PRIMARY KEY AUTO_INCREMENT COMMENT '主键ID',
  assistant_name VARCHAR(100) NOT NULL DEFAULT '百华工艺助手' COMMENT '助手名称',
  provider_name VARCHAR(100) NULL COMMENT 'LLM供应商名称',
  api_base_url VARCHAR(255) NULL COMMENT 'LLM API基础地址',
  api_key VARCHAR(512) NULL COMMENT 'LLM API密钥',
  model_name VARCHAR(100) NULL COMMENT '模型名称',
  temperature DECIMAL(6,3) NOT NULL DEFAULT 0.300 COMMENT '温度参数',
  system_prompt TEXT NULL COMMENT '新建对话系统提示词',
  enabled TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否启用真实LLM',
  created_by BIGINT NULL COMMENT '创建用户ID',
  updated_by BIGINT NULL COMMENT '更新用户ID',
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  CONSTRAINT fk_ai_config_created_by FOREIGN KEY (created_by) REFERENCES sys_user(id),
  CONSTRAINT fk_ai_config_updated_by FOREIGN KEY (updated_by) REFERENCES sys_user(id)
) ENGINE=InnoDB COMMENT='AI助手配置';

INSERT INTO sys_permission (permission_code, permission_name, module_code, action_code, status)
SELECT 'MENU_SYSTEM_EXTENSION', '系统拓展菜单', 'SYSTEM_EXTENSION', 'VIEW', 'ACTIVE'
FROM DUAL
WHERE NOT EXISTS (SELECT 1 FROM sys_permission WHERE permission_code = 'MENU_SYSTEM_EXTENSION');

INSERT INTO sys_role_permission (role_id, permission_id)
SELECT r.id, p.id
FROM sys_role r
JOIN sys_permission p ON p.permission_code = 'MENU_SYSTEM_EXTENSION'
LEFT JOIN sys_role_permission existing ON existing.role_id = r.id AND existing.permission_id = p.id
WHERE r.role_code = 'ADMIN'
  AND existing.id IS NULL;

INSERT INTO sys_broadcast_message (title, content, tone, status, sort_no)
SELECT '系统提示', '系统拓展模块已启用，后续通知会在右上角喇叭横幅展示。', 'INFO', 'ACTIVE', 10
FROM DUAL
WHERE NOT EXISTS (SELECT 1 FROM sys_broadcast_message);
