-- ===========================================
-- 班级操行分管理系统 - v1.0 → v1.1 升级脚本
-- 字符集: utf8mb4
--
-- 变更内容:
--   1. users 表添加 need_change_password 列
--   2. users 表添加 last_login_time 列
--   3. users 表添加 last_login_ip 列
--   4. users 表 password_hash 字段扩展至 VARCHAR(255)
--
-- 兼容性: 使用存储过程实现幂等，phpMyAdmin 可直接执行
-- ===========================================

-- 升级步骤 1: users 添加 need_change_password 列
DROP PROCEDURE IF EXISTS `upgrade_step`;
DELIMITER $$
CREATE PROCEDURE `upgrade_step`()
BEGIN
    IF NOT EXISTS (
        SELECT * FROM INFORMATION_SCHEMA.COLUMNS 
        WHERE TABLE_SCHEMA = DATABASE() 
          AND TABLE_NAME = 'users' 
          AND COLUMN_NAME = 'need_change_password'
    ) THEN
        ALTER TABLE `users` 
        ADD COLUMN `need_change_password` TINYINT DEFAULT 1 
        AFTER `status`;
    END IF;
END$$
DELIMITER ;

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

-- 升级步骤 2: users 添加 last_login_time 列
DROP PROCEDURE IF EXISTS `upgrade_step`;
DELIMITER $$
CREATE PROCEDURE `upgrade_step`()
BEGIN
    IF NOT EXISTS (
        SELECT * FROM INFORMATION_SCHEMA.COLUMNS 
        WHERE TABLE_SCHEMA = DATABASE() 
          AND TABLE_NAME = 'users' 
          AND COLUMN_NAME = 'last_login_time'
    ) THEN
        ALTER TABLE `users` 
        ADD COLUMN `last_login_time` DATETIME DEFAULT NULL 
        AFTER `need_change_password`;
    END IF;
END$$
DELIMITER ;

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

-- 升级步骤 3: users 添加 last_login_ip 列
DROP PROCEDURE IF EXISTS `upgrade_step`;
DELIMITER $$
CREATE PROCEDURE `upgrade_step`()
BEGIN
    IF NOT EXISTS (
        SELECT * FROM INFORMATION_SCHEMA.COLUMNS 
        WHERE TABLE_SCHEMA = DATABASE() 
          AND TABLE_NAME = 'users' 
          AND COLUMN_NAME = 'last_login_ip'
    ) THEN
        ALTER TABLE `users` 
        ADD COLUMN `last_login_ip` VARCHAR(45) DEFAULT NULL 
        AFTER `last_login_time`;
    END IF;
END$$
DELIMITER ;

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

-- 升级步骤 4: password_hash 字段扩展至 VARCHAR(255)
DROP PROCEDURE IF EXISTS `upgrade_step`;
DELIMITER $$
CREATE PROCEDURE `upgrade_step`()
BEGIN
    DECLARE v_col_len INT;
    SELECT CHARACTER_MAXIMUM_LENGTH INTO v_col_len
    FROM INFORMATION_SCHEMA.COLUMNS 
    WHERE TABLE_SCHEMA = DATABASE() 
      AND TABLE_NAME = 'users' 
      AND COLUMN_NAME = 'password_hash';
    
    IF v_col_len < 255 THEN
        ALTER TABLE `users` 
        MODIFY COLUMN `password_hash` VARCHAR(255) NOT NULL;
    END IF;
END$$
DELIMITER ;

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