-- 新分销逻辑数据库迁移脚本
-- 为 referral_bindings 表添加新字段

-- 1. 添加新字段
ALTER TABLE referral_bindings 
ADD COLUMN IF NOT EXISTS last_purchase_date DATETIME NULL COMMENT '最后一次购买时间',
ADD COLUMN IF NOT EXISTS purchase_count INT DEFAULT 0 COMMENT '购买次数',
ADD COLUMN IF NOT EXISTS total_commission DECIMAL(10,2) DEFAULT 0.00 COMMENT '累计佣金';

-- 2. 添加索引优化查询
ALTER TABLE referral_bindings 
ADD INDEX IF NOT EXISTS idx_referee_status (referee_id, status),
ADD INDEX IF NOT EXISTS idx_expiry_purchase (expiry_date, purchase_count, status);

-- 3. 修改 status 枚举（添加 cancelled 状态）
ALTER TABLE referral_bindings 
MODIFY COLUMN status ENUM('active', 'converted', 'expired', 'cancelled') DEFAULT 'active' COMMENT '绑定状态';

-- 4. 验证字段已添加
SHOW COLUMNS FROM referral_bindings LIKE 'last_purchase_date';
SHOW COLUMNS FROM referral_bindings LIKE 'purchase_count';
SHOW COLUMNS FROM referral_bindings LIKE 'total_commission';

-- 5. 查看索引
SHOW INDEX FROM referral_bindings;
