-- ============================================
-- 星域故事汇 完整数据库结构 V2.0
-- 支持：AI改写/续写/创作、UGC、社交、计费
-- ============================================

CREATE DATABASE IF NOT EXISTS stardom_story DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
USE stardom_story;

-- ============================================
-- 一、用户体系
-- ============================================

-- 用户主表
CREATE TABLE users (
  id BIGINT PRIMARY KEY AUTO_INCREMENT,
  openid VARCHAR(100) UNIQUE NOT NULL COMMENT '微信openid',
  unionid VARCHAR(100) DEFAULT '' COMMENT '微信unionid',
  nickname VARCHAR(100) DEFAULT '' COMMENT '昵称',
  avatar_url VARCHAR(500) DEFAULT '' COMMENT '头像',
  gender TINYINT DEFAULT 0 COMMENT '0未知 1男 2女',
  phone VARCHAR(20) DEFAULT '' COMMENT '手机号',
  level INT DEFAULT 1 COMMENT '用户等级',
  exp INT DEFAULT 0 COMMENT '经验值',
  vip_type TINYINT DEFAULT 0 COMMENT '0普通 1月卡 2年卡 3永久',
  vip_expire_at DATETIME DEFAULT NULL COMMENT 'VIP过期时间',
  coin_balance INT DEFAULT 0 COMMENT '金币余额',
  is_creator BOOLEAN DEFAULT FALSE COMMENT '是否认证创作者',
  is_banned BOOLEAN DEFAULT FALSE COMMENT '是否封禁',
  ban_reason VARCHAR(255) DEFAULT '',
  last_login_at DATETIME DEFAULT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  INDEX idx_openid (openid),
  INDEX idx_unionid (unionid),
  INDEX idx_creator (is_creator)
) ENGINE=InnoDB COMMENT='用户主表';

-- 用户统计表（高频更新分离）
CREATE TABLE user_stats (
  user_id BIGINT PRIMARY KEY,
  total_play_count INT DEFAULT 0 COMMENT '总游玩次数',
  total_endings INT DEFAULT 0 COMMENT '解锁结局数',
  total_creations INT DEFAULT 0 COMMENT '创作数',
  total_ai_uses INT DEFAULT 0 COMMENT 'AI使用次数',
  followers_count INT DEFAULT 0 COMMENT '粉丝数',
  following_count INT DEFAULT 0 COMMENT '关注数',
  likes_received INT DEFAULT 0 COMMENT '获赞数',
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB COMMENT='用户统计表';

-- 用户关注关系表
CREATE TABLE user_follows (
  id BIGINT PRIMARY KEY AUTO_INCREMENT,
  follower_id BIGINT NOT NULL COMMENT '关注者',
  following_id BIGINT NOT NULL COMMENT '被关注者',
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  UNIQUE KEY uk_follow (follower_id, following_id),
  INDEX idx_follower (follower_id),
  INDEX idx_following (following_id)
) ENGINE=InnoDB COMMENT='用户关注关系';

-- ============================================
-- 二、故事内容体系
-- ============================================

-- 故事主表（官方+UGC统一）
CREATE TABLE stories (
  id BIGINT PRIMARY KEY AUTO_INCREMENT,
  author_id BIGINT DEFAULT 0 COMMENT '作者ID，0为官方',
  title VARCHAR(100) NOT NULL COMMENT '标题',
  cover_url VARCHAR(500) DEFAULT '' COMMENT '封面',
  description TEXT COMMENT '简介',
  category VARCHAR(50) NOT NULL COMMENT '分类',
  tags VARCHAR(255) DEFAULT '' COMMENT '标签，逗号分隔',
  word_count INT DEFAULT 0 COMMENT '字数',
  node_count INT DEFAULT 0 COMMENT '节点数',
  ending_count INT DEFAULT 0 COMMENT '结局数',
  difficulty TINYINT DEFAULT 2 COMMENT '难度 1简单 2普通 3困难',
  
  -- 来源标记
  source_type ENUM('official','ugc','ai_generated','ai_assisted') DEFAULT 'official' COMMENT '来源类型',
  base_story_id BIGINT DEFAULT NULL COMMENT '基于哪个故事改编',
  ai_generation_id BIGINT DEFAULT NULL COMMENT '关联的AI生成记录',
  
  -- 状态控制
  status TINYINT DEFAULT 0 COMMENT '0草稿 1审核中 2已发布 3已下架 4已拒绝',
  review_note VARCHAR(500) DEFAULT '' COMMENT '审核备注',
  is_featured BOOLEAN DEFAULT FALSE COMMENT '是否精选',
  is_hot BOOLEAN DEFAULT FALSE COMMENT '是否热门',
  is_new BOOLEAN DEFAULT TRUE COMMENT '是否新作',
  
  -- 付费设置
  price_type TINYINT DEFAULT 0 COMMENT '0免费 1付费 2广告解锁',
  price_coin INT DEFAULT 0 COMMENT '价格(金币)',
  free_chapters INT DEFAULT 0 COMMENT '免费章节数',
  
  -- 统计（读多写少可放主表）
  play_count INT DEFAULT 0,
  like_count INT DEFAULT 0,
  collect_count INT DEFAULT 0,
  comment_count INT DEFAULT 0,
  share_count INT DEFAULT 0,
  
  published_at DATETIME DEFAULT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  
  INDEX idx_author (author_id),
  INDEX idx_category (category),
  INDEX idx_status (status),
  INDEX idx_source (source_type),
  INDEX idx_featured (is_featured),
  INDEX idx_play (play_count),
  INDEX idx_created (created_at)
) ENGINE=InnoDB COMMENT='故事主表';

-- 故事节点表
CREATE TABLE story_nodes (
  id BIGINT PRIMARY KEY AUTO_INCREMENT,
  story_id BIGINT NOT NULL,
  node_key VARCHAR(50) NOT NULL COMMENT '节点标识',
  parent_node_key VARCHAR(50) DEFAULT '' COMMENT '父节点（用于树形结构）',
  chapter_num INT DEFAULT 1 COMMENT '章节号',
  
  -- 内容
  content TEXT NOT NULL COMMENT '文本内容',
  speaker VARCHAR(50) DEFAULT '' COMMENT '说话角色',
  emotion VARCHAR(30) DEFAULT '' COMMENT '情绪标签',
  
  -- 媒体资源
  background_image VARCHAR(500) DEFAULT '',
  character_images JSON DEFAULT NULL COMMENT '角色立绘数组',
  bgm VARCHAR(500) DEFAULT '',
  sound_effect VARCHAR(500) DEFAULT '',
  voice_url VARCHAR(500) DEFAULT '' COMMENT '语音URL',
  
  -- 结局设置
  is_ending BOOLEAN DEFAULT FALSE,
  ending_name VARCHAR(100) DEFAULT '',
  ending_type ENUM('good','bad','normal','hidden','secret') DEFAULT 'normal',
  ending_score INT DEFAULT 0,
  ending_cg VARCHAR(500) DEFAULT '' COMMENT '结局CG图',
  
  -- AI标记
  is_ai_generated BOOLEAN DEFAULT FALSE,
  ai_generation_id BIGINT DEFAULT NULL,
  
  sort_order INT DEFAULT 0,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  
  INDEX idx_story (story_id),
  INDEX idx_node_key (story_id, node_key),
  INDEX idx_chapter (story_id, chapter_num),
  FOREIGN KEY (story_id) REFERENCES stories(id) ON DELETE CASCADE
) ENGINE=InnoDB COMMENT='故事节点表';

-- 故事选项表
CREATE TABLE story_choices (
  id BIGINT PRIMARY KEY AUTO_INCREMENT,
  story_id BIGINT NOT NULL,
  node_id BIGINT NOT NULL,
  text VARCHAR(200) NOT NULL COMMENT '选项文本',
  next_node_key VARCHAR(50) NOT NULL,
  
  -- 条件解锁
  condition_type ENUM('none','item','attr','ending','vip','ad') DEFAULT 'none',
  condition_value VARCHAR(100) DEFAULT '' COMMENT '条件值JSON',
  
  -- 效果
  effect_type ENUM('none','attr','item','achievement') DEFAULT 'none',
  effect_value VARCHAR(100) DEFAULT '' COMMENT '效果值JSON',
  
  -- AI标记
  is_ai_generated BOOLEAN DEFAULT FALSE,
  
  sort_order INT DEFAULT 0,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  
  INDEX idx_story (story_id),
  INDEX idx_node (node_id),
  FOREIGN KEY (story_id) REFERENCES stories(id) ON DELETE CASCADE,
  FOREIGN KEY (node_id) REFERENCES story_nodes(id) ON DELETE CASCADE
) ENGINE=InnoDB COMMENT='故事选项表';

-- 故事版本表（支持版本回退）
CREATE TABLE story_versions (
  id BIGINT PRIMARY KEY AUTO_INCREMENT,
  story_id BIGINT NOT NULL,
  version_num INT NOT NULL COMMENT '版本号',
  nodes_snapshot LONGTEXT NOT NULL COMMENT '节点快照JSON',
  change_log VARCHAR(500) DEFAULT '' COMMENT '变更说明',
  created_by BIGINT NOT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  UNIQUE KEY uk_version (story_id, version_num),
  INDEX idx_story (story_id)
) ENGINE=InnoDB COMMENT='故事版本表';

-- ============================================
-- 三、AI生成体系
-- ============================================

-- AI生成记录表
CREATE TABLE ai_generations (
  id BIGINT PRIMARY KEY AUTO_INCREMENT,
  user_id BIGINT NOT NULL,
  story_id BIGINT DEFAULT NULL COMMENT '关联故事',
  
  -- 生成类型
  gen_type ENUM('rewrite_ending','rewrite_node','continue','create_outline','create_full','polish','translate') NOT NULL,
  
  -- 输入
  source_node_key VARCHAR(50) DEFAULT '',
  source_content TEXT COMMENT '原内容',
  user_prompt TEXT NOT NULL COMMENT '用户指令',
  system_prompt TEXT COMMENT '系统提示词',
  
  -- 输出
  generated_content LONGTEXT COMMENT '生成内容',
  generated_nodes JSON COMMENT '生成的节点结构',
  
  -- 模型信息
  model_provider VARCHAR(30) DEFAULT '' COMMENT 'openai/anthropic/local',
  model_name VARCHAR(50) DEFAULT '',
  temperature DECIMAL(3,2) DEFAULT 0.70,
  
  -- 消耗统计
  input_tokens INT DEFAULT 0,
  output_tokens INT DEFAULT 0,
  total_tokens INT DEFAULT 0,
  latency_ms INT DEFAULT 0 COMMENT '响应耗时',
  cost_cents INT DEFAULT 0 COMMENT '成本(分)',
  
  -- 状态
  status TINYINT DEFAULT 1 COMMENT '0失败 1成功 2处理中',
  error_code VARCHAR(50) DEFAULT '',
  error_msg TEXT,
  
  -- 用户操作
  is_accepted BOOLEAN DEFAULT NULL COMMENT '用户是否采纳',
  is_edited BOOLEAN DEFAULT FALSE COMMENT '是否编辑后使用',
  is_published BOOLEAN DEFAULT FALSE COMMENT '是否发布',
  
  -- 评价
  user_rating TINYINT DEFAULT NULL COMMENT '1-5星评价',
  user_feedback TEXT COMMENT '用户反馈',
  
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  INDEX idx_user (user_id),
  INDEX idx_story (story_id),
  INDEX idx_type (gen_type),
  INDEX idx_status (status),
  INDEX idx_created (created_at)
) ENGINE=InnoDB COMMENT='AI生成记录表';

-- AI提示词模板表
CREATE TABLE ai_prompt_templates (
  id INT PRIMARY KEY AUTO_INCREMENT,
  name VARCHAR(100) NOT NULL,
  gen_type VARCHAR(30) NOT NULL,
  category VARCHAR(50) DEFAULT '' COMMENT '适用分类',
  system_prompt TEXT NOT NULL,
  user_prompt_template TEXT NOT NULL COMMENT '用户提示词模板',
  variables JSON COMMENT '可用变量说明',
  model_recommend VARCHAR(50) DEFAULT '',
  temperature_recommend DECIMAL(3,2) DEFAULT 0.70,
  is_active BOOLEAN DEFAULT TRUE,
  sort_order INT DEFAULT 0,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  INDEX idx_type (gen_type),
  INDEX idx_active (is_active)
) ENGINE=InnoDB COMMENT='AI提示词模板';

-- ============================================
-- 四、用户行为体系
-- ============================================

-- 用户游玩进度表
CREATE TABLE user_progress (
  id BIGINT PRIMARY KEY AUTO_INCREMENT,
  user_id BIGINT NOT NULL,
  story_id BIGINT NOT NULL,
  current_node_key VARCHAR(50) DEFAULT 'start',
  
  -- 状态
  status TINYINT DEFAULT 0 COMMENT '0进行中 1已完成',
  play_count INT DEFAULT 1,
  play_duration INT DEFAULT 0 COMMENT '游玩时长(秒)',
  
  -- 达成结局
  endings_reached JSON COMMENT '达成的结局列表',
  best_ending_score INT DEFAULT 0,
  
  -- 存档数据
  save_data JSON COMMENT '游戏存档(属性/道具等)',
  choices_history JSON COMMENT '选择历史',
  
  -- 互动
  is_liked BOOLEAN DEFAULT FALSE,
  is_collected BOOLEAN DEFAULT FALSE,
  
  first_play_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  last_play_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  completed_at DATETIME DEFAULT NULL,
  
  UNIQUE KEY uk_user_story (user_id, story_id),
  INDEX idx_user (user_id),
  INDEX idx_story (story_id),
  INDEX idx_status (status)
) ENGINE=InnoDB COMMENT='用户游玩进度';

-- 用户结局收集表
CREATE TABLE user_endings (
  id BIGINT PRIMARY KEY AUTO_INCREMENT,
  user_id BIGINT NOT NULL,
  story_id BIGINT NOT NULL,
  node_id BIGINT NOT NULL,
  ending_name VARCHAR(100) NOT NULL,
  ending_type VARCHAR(20) DEFAULT 'normal',
  ending_score INT DEFAULT 0,
  choices_path JSON COMMENT '达成路径',
  play_duration INT DEFAULT 0 COMMENT '本次游玩时长',
  unlocked_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  UNIQUE KEY uk_user_ending (user_id, story_id, ending_name),
  INDEX idx_user (user_id),
  INDEX idx_story (story_id)
) ENGINE=InnoDB COMMENT='用户结局收集';

-- 用户收藏表
CREATE TABLE user_collections (
  id BIGINT PRIMARY KEY AUTO_INCREMENT,
  user_id BIGINT NOT NULL,
  story_id BIGINT NOT NULL,
  folder_name VARCHAR(50) DEFAULT '默认' COMMENT '收藏夹',
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  UNIQUE KEY uk_user_story (user_id, story_id),
  INDEX idx_user (user_id),
  INDEX idx_folder (user_id, folder_name)
) ENGINE=InnoDB COMMENT='用户收藏';

-- 评论表
CREATE TABLE comments (
  id BIGINT PRIMARY KEY AUTO_INCREMENT,
  user_id BIGINT NOT NULL,
  story_id BIGINT NOT NULL,
  parent_id BIGINT DEFAULT NULL COMMENT '父评论ID',
  reply_to_user_id BIGINT DEFAULT NULL COMMENT '回复谁',
  content TEXT NOT NULL,
  like_count INT DEFAULT 0,
  status TINYINT DEFAULT 1 COMMENT '0隐藏 1正常 2置顶',
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  INDEX idx_story (story_id),
  INDEX idx_user (user_id),
  INDEX idx_parent (parent_id)
) ENGINE=InnoDB COMMENT='评论表';

-- ============================================
-- 五、经济体系
-- ============================================

-- 用户AI配额表
CREATE TABLE user_ai_quota (
  user_id BIGINT PRIMARY KEY,
  
  -- 每日免费额度
  daily_free_total INT DEFAULT 5 COMMENT '每日免费总次数',
  daily_free_used INT DEFAULT 0 COMMENT '今日已用',
  daily_reset_date DATE COMMENT '重置日期',
  
  -- 购买/赠送额度
  purchased_quota INT DEFAULT 0 COMMENT '购买的次数',
  gift_quota INT DEFAULT 0 COMMENT '赠送的次数',
  
  -- VIP额度
  vip_daily_bonus INT DEFAULT 0 COMMENT 'VIP每日额外次数',
  
  -- 总使用统计
  total_used INT DEFAULT 0,
  total_tokens_used BIGINT DEFAULT 0,
  
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB COMMENT='用户AI配额';

-- 金币流水表
CREATE TABLE coin_transactions (
  id BIGINT PRIMARY KEY AUTO_INCREMENT,
  user_id BIGINT NOT NULL,
  amount INT NOT NULL COMMENT '正为收入负为支出',
  balance_after INT NOT NULL COMMENT '交易后余额',
  
  tx_type ENUM('recharge','purchase','reward','refund','gift','withdraw') NOT NULL,
  ref_type VARCHAR(30) DEFAULT '' COMMENT '关联类型',
  ref_id BIGINT DEFAULT NULL COMMENT '关联ID',
  
  description VARCHAR(255) DEFAULT '',
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  INDEX idx_user (user_id),
  INDEX idx_type (tx_type),
  INDEX idx_created (created_at)
) ENGINE=InnoDB COMMENT='金币流水';

-- 订单表
CREATE TABLE orders (
  id BIGINT PRIMARY KEY AUTO_INCREMENT,
  order_no VARCHAR(64) UNIQUE NOT NULL,
  user_id BIGINT NOT NULL,
  
  product_type ENUM('coin','vip','story','ai_quota') NOT NULL,
  product_id VARCHAR(50) DEFAULT '',
  product_name VARCHAR(100) NOT NULL,
  
  amount_cents INT NOT NULL COMMENT '金额(分)',
  pay_channel VARCHAR(30) DEFAULT '' COMMENT '支付渠道',
  
  status TINYINT DEFAULT 0 COMMENT '0待支付 1已支付 2已取消 3已退款',
  paid_at DATETIME DEFAULT NULL,
  
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  INDEX idx_user (user_id),
  INDEX idx_order_no (order_no),
  INDEX idx_status (status)
) ENGINE=InnoDB COMMENT='订单表';

-- ============================================
-- 六、运营与审核
-- ============================================

-- 内容审核表
CREATE TABLE content_reviews (
  id BIGINT PRIMARY KEY AUTO_INCREMENT,
  content_type ENUM('story','comment','ai_generation','avatar','nickname') NOT NULL,
  content_id BIGINT NOT NULL,
  user_id BIGINT NOT NULL COMMENT '提交者',
  
  content_snapshot TEXT COMMENT '内容快照',
  
  -- 机审
  auto_result TINYINT DEFAULT NULL COMMENT '0通过 1疑似 2违规',
  auto_labels JSON COMMENT '机审标签',
  auto_score DECIMAL(5,2) DEFAULT NULL,
  
  -- 人审
  review_status TINYINT DEFAULT 0 COMMENT '0待审 1通过 2拒绝',
  reviewer_id BIGINT DEFAULT NULL,
  review_note VARCHAR(500) DEFAULT '',
  reviewed_at DATETIME DEFAULT NULL,
  
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  INDEX idx_type_status (content_type, review_status),
  INDEX idx_user (user_id),
  INDEX idx_created (created_at)
) ENGINE=InnoDB COMMENT='内容审核表';

-- 举报表
CREATE TABLE reports (
  id BIGINT PRIMARY KEY AUTO_INCREMENT,
  reporter_id BIGINT NOT NULL,
  target_type ENUM('story','comment','user') NOT NULL,
  target_id BIGINT NOT NULL,
  reason_type VARCHAR(30) NOT NULL COMMENT '举报类型',
  reason_detail TEXT,
  
  status TINYINT DEFAULT 0 COMMENT '0待处理 1已处理 2已忽略',
  handler_id BIGINT DEFAULT NULL,
  handle_result VARCHAR(255) DEFAULT '',
  handled_at DATETIME DEFAULT NULL,
  
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  INDEX idx_target (target_type, target_id),
  INDEX idx_status (status)
) ENGINE=InnoDB COMMENT='举报表';

-- ============================================
-- 七、数据分析
-- ============================================

-- 行为埋点表（按天分区）
CREATE TABLE event_logs (
  id BIGINT PRIMARY KEY AUTO_INCREMENT,
  user_id BIGINT DEFAULT NULL,
  device_id VARCHAR(100) DEFAULT '',
  session_id VARCHAR(64) DEFAULT '',
  
  event_name VARCHAR(50) NOT NULL,
  event_params JSON,
  
  page_name VARCHAR(50) DEFAULT '',
  ref_page VARCHAR(50) DEFAULT '',
  
  platform VARCHAR(20) DEFAULT '' COMMENT 'weapp/h5/app',
  app_version VARCHAR(20) DEFAULT '',
  os VARCHAR(20) DEFAULT '',
  device_model VARCHAR(50) DEFAULT '',
  
  ip VARCHAR(50) DEFAULT '',
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  event_date DATE AS (DATE(created_at)) STORED,
  
  INDEX idx_user (user_id),
  INDEX idx_event (event_name),
  INDEX idx_date (event_date),
  INDEX idx_session (session_id)
) ENGINE=InnoDB COMMENT='行为埋点表'
PARTITION BY RANGE (TO_DAYS(event_date)) (
  PARTITION p_default VALUES LESS THAN MAXVALUE
);

-- AI调用统计日表
CREATE TABLE ai_daily_stats (
  id INT PRIMARY KEY AUTO_INCREMENT,
  stat_date DATE NOT NULL,
  gen_type VARCHAR(30) NOT NULL,
  model_name VARCHAR(50) DEFAULT '',
  
  call_count INT DEFAULT 0,
  success_count INT DEFAULT 0,
  fail_count INT DEFAULT 0,
  
  total_input_tokens BIGINT DEFAULT 0,
  total_output_tokens BIGINT DEFAULT 0,
  total_cost_cents INT DEFAULT 0,
  
  avg_latency_ms INT DEFAULT 0,
  p99_latency_ms INT DEFAULT 0,
  
  unique_users INT DEFAULT 0,
  
  UNIQUE KEY uk_date_type (stat_date, gen_type, model_name),
  INDEX idx_date (stat_date)
) ENGINE=InnoDB COMMENT='AI调用日统计';

-- ============================================
-- 八、系统配置
-- ============================================

-- 分类配置表
CREATE TABLE categories (
  id INT PRIMARY KEY AUTO_INCREMENT,
  name VARCHAR(50) NOT NULL,
  icon VARCHAR(100) DEFAULT '',
  color VARCHAR(20) DEFAULT '',
  sort_order INT DEFAULT 0,
  is_active BOOLEAN DEFAULT TRUE,
  story_count INT DEFAULT 0,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB COMMENT='分类配置';

-- 系统配置表
CREATE TABLE system_configs (
  config_key VARCHAR(100) PRIMARY KEY,
  config_value TEXT NOT NULL,
  description VARCHAR(255) DEFAULT '',
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB COMMENT='系统配置';

-- 敏感词表
CREATE TABLE sensitive_words (
  id INT PRIMARY KEY AUTO_INCREMENT,
  word VARCHAR(50) NOT NULL,
  category VARCHAR(30) DEFAULT 'general',
  level TINYINT DEFAULT 1 COMMENT '1警告 2禁止',
  is_active BOOLEAN DEFAULT TRUE,
  UNIQUE KEY uk_word (word),
  INDEX idx_category (category)
) ENGINE=InnoDB COMMENT='敏感词表';

-- ============================================
-- 九、AI改写草稿箱
-- ============================================

-- AI改写草稿表
CREATE TABLE story_drafts (
  id BIGINT PRIMARY KEY AUTO_INCREMENT,
  user_id BIGINT NOT NULL COMMENT '用户ID',
  story_id BIGINT NOT NULL COMMENT '原故事ID',
  title VARCHAR(100) DEFAULT '' COMMENT '草稿标题',
  
  -- 用户输入
  path_history JSON COMMENT '用户之前的选择路径',
  current_node_key VARCHAR(50) DEFAULT '' COMMENT '改写起始节点',
  current_content TEXT COMMENT '当前节点内容',
  user_prompt VARCHAR(500) NOT NULL COMMENT '用户改写指令',
  
  -- AI生成结果
  ai_nodes JSON COMMENT 'AI生成的新节点',
  entry_node_key VARCHAR(50) DEFAULT '' COMMENT '入口节点',
  tokens_used INT DEFAULT 0 COMMENT '消耗token数',
  
  -- 状态
  status ENUM('pending', 'processing', 'completed', 'failed') DEFAULT 'pending' COMMENT '状态',
  error_message VARCHAR(500) DEFAULT '' COMMENT '失败原因',
  is_read BOOLEAN DEFAULT FALSE COMMENT '用户是否已查看',
  
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  completed_at TIMESTAMP NULL COMMENT '完成时间',
  
  INDEX idx_user (user_id),
  INDEX idx_story (story_id),
  INDEX idx_status (status),
  INDEX idx_user_unread (user_id, is_read)
) ENGINE=InnoDB COMMENT='AI改写草稿表';
