-- ============================================================
-- 迁移脚本: v10.3.1 隐私权管理增强
-- 创建时间: 2026-06-27
-- 描述: 新增用户同意管理表、注销进度字段、用户出生日期字段
-- 兼容: MySQL 5.7+ (不使用 ADD COLUMN IF NOT EXISTS 语法)
-- ============================================================

-- 1. 用户数据处理同意表 (GDPR/PIPL合规)
CREATE TABLE IF NOT EXISTS `tool_user_consents` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL DEFAULT '0' COMMENT '用户ID',
  `consent_type` varchar(50) NOT NULL DEFAULT '' COMMENT '同意类型: analytics/marketing/personalization/third_party_share',
  `consent_value` tinyint(1) NOT NULL DEFAULT '1' COMMENT '0=拒绝 1=同意',
  `consent_source` varchar(20) NOT NULL DEFAULT 'web' COMMENT '来源: web/app/system',
  `ip` varchar(50) DEFAULT '' COMMENT 'IP地址',
  `createtime` int(11) DEFAULT NULL COMMENT '创建时间',
  `updatetime` int(11) DEFAULT NULL COMMENT '更新时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_user_type` (`user_id`,`consent_type`),
  KEY `idx_user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户数据处理同意记录';

-- 2. user_deletion表新增注销进度字段 (使用存储过程兼容MySQL 5.7)
DROP PROCEDURE IF EXISTS `migrate_v10_3_add_columns`;
DELIMITER $$
CREATE PROCEDURE `migrate_v10_3_add_columns`()
BEGIN
    -- tool_user_deletion: deletion_progress
    IF NOT EXISTS (SELECT 1 FROM information_schema.COLUMNS
                   WHERE TABLE_SCHEMA = DATABASE()
                     AND TABLE_NAME = 'tool_user_deletion'
                     AND COLUMN_NAME = 'deletion_progress') THEN
        ALTER TABLE `tool_user_deletion` ADD COLUMN `deletion_progress` text COMMENT '注销进度JSON' AFTER `admin_remark`;
    END IF;

    -- tool_user_deletion: deletion_summary
    IF NOT EXISTS (SELECT 1 FROM information_schema.COLUMNS
                   WHERE TABLE_SCHEMA = DATABASE()
                     AND TABLE_NAME = 'tool_user_deletion'
                     AND COLUMN_NAME = 'deletion_summary') THEN
        ALTER TABLE `tool_user_deletion` ADD COLUMN `deletion_summary` varchar(500) DEFAULT '' COMMENT '注销数据摘要' AFTER `deletion_progress`;
    END IF;

    -- tool_user: birthday
    IF NOT EXISTS (SELECT 1 FROM information_schema.COLUMNS
                   WHERE TABLE_SCHEMA = DATABASE()
                     AND TABLE_NAME = 'tool_user'
                     AND COLUMN_NAME = 'birthday') THEN
        ALTER TABLE `tool_user` ADD COLUMN `birthday` date DEFAULT NULL COMMENT '出生日期' AFTER `email`;
    END IF;

    -- tool_user: is_minor
    IF NOT EXISTS (SELECT 1 FROM information_schema.COLUMNS
                   WHERE TABLE_SCHEMA = DATABASE()
                     AND TABLE_NAME = 'tool_user'
                     AND COLUMN_NAME = 'is_minor') THEN
        ALTER TABLE `tool_user` ADD COLUMN `is_minor` tinyint(1) NOT NULL DEFAULT '0' COMMENT '是否未成年: 0=成年 1=未成年(需家长控制)' AFTER `birthday`;
    END IF;
END$$
DELIMITER ;

CALL `migrate_v10_3_add_columns`();
DROP PROCEDURE IF EXISTS `migrate_v10_3_add_columns`;
