-- ============================================
-- 修复 OAuth2 access_token 字段长度不足的问题
-- 问题：access_token 字段长度只有 1024，但生成的 JWT token 超过此长度
-- 解决：将 access_token 字段长度增加到 2048
-- ============================================

-- 修改 xdz_user 数据库中的 system_oauth2_access_token 表
USE xdz_user;

-- 删除旧的索引（如果存在，使用存储过程方式兼容不同 MySQL 版本）
SET @index_exists = (SELECT COUNT(*) FROM information_schema.statistics 
  WHERE table_schema = 'xdz_user' 
  AND table_name = 'system_oauth2_access_token' 
  AND index_name = 'idx_access_token');

SET @sql = IF(@index_exists > 0, 
  'ALTER TABLE `system_oauth2_access_token` DROP INDEX `idx_access_token`', 
  'SELECT 1');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- 修改 access_token 字段长度
ALTER TABLE `system_oauth2_access_token` 
MODIFY COLUMN `access_token` varchar(2048) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '访问令牌';

-- 重新创建索引（使用前缀索引，因为字段太长）
ALTER TABLE `system_oauth2_access_token` 
ADD INDEX `idx_access_token`(`access_token`(255)) USING BTREE;

-- ============================================
-- 如果 xdz_business 数据库也有此表，也需要修改
-- ============================================
USE xdz_business;

-- 检查表是否存在，如果存在则修改
SET @table_exists = (SELECT COUNT(*) FROM information_schema.tables 
  WHERE table_schema = 'xdz_business' 
  AND table_name = 'system_oauth2_access_token');

SET @index_exists = IF(@table_exists > 0, 
  (SELECT COUNT(*) FROM information_schema.statistics 
   WHERE table_schema = 'xdz_business' 
   AND table_name = 'system_oauth2_access_token' 
   AND index_name = 'idx_access_token'), 
  0);

SET @sql = IF(@table_exists > 0 AND @index_exists > 0, 
  'ALTER TABLE `system_oauth2_access_token` DROP INDEX `idx_access_token`', 
  'SELECT 1');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @sql = IF(@table_exists > 0, 
  'ALTER TABLE `system_oauth2_access_token` MODIFY COLUMN `access_token` varchar(2048) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT ''访问令牌''', 
  'SELECT 1');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @sql = IF(@table_exists > 0, 
  'ALTER TABLE `system_oauth2_access_token` ADD INDEX `idx_access_token`(`access_token`(255)) USING BTREE', 
  'SELECT 1');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

