<?php
/**
 * 认证模块数据库迁移脚本
 * 添加 login_attempts / locked_until 字段，创建 remember_tokens 表
 * 同时兼容 MySQL 和 SQLite
 */
require_once __DIR__ . '/../config.php';

$isSqlite = (file_exists(__DIR__ . '/../.use_sqlite') && trim(file_get_contents(__DIR__ . '/../.use_sqlite')) === '1');

try {
    // ---- 1. users 表追加字段 ----
    if ($isSqlite) {
        // SQLite: ALTER TABLE 不支持 IF NOT EXISTS / 多列，逐个加并用 try 包裹
        $sqliteAlters = [
            "ALTER TABLE users ADD COLUMN login_attempts INTEGER DEFAULT 0",
            "ALTER TABLE users ADD COLUMN locked_until TIMESTAMP DEFAULT NULL",
        ];
        foreach ($sqliteAlters as $sql) {
            try {
                $pdo->exec($sql);
            } catch (PDOException $e) {
                // 字段已存在时忽略
            }
        }
    } else {
        // MySQL
        $pdo->exec("ALTER TABLE users ADD COLUMN IF NOT EXISTS login_attempts INT DEFAULT 0");
        $pdo->exec("ALTER TABLE users ADD COLUMN IF NOT EXISTS locked_until DATETIME DEFAULT NULL");
    }
    echo "✓ users 表字段检查完成\n";

    // ---- 2. 创建 remember_tokens 表 ----
    if ($isSqlite) {
        $pdo->exec("CREATE TABLE IF NOT EXISTS remember_tokens (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            user_id INTEGER NOT NULL,
            token_hash VARCHAR(64) NOT NULL,
            expires_at TIMESTAMP NOT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
        )");
    } else {
        $pdo->exec("CREATE TABLE IF NOT EXISTS remember_tokens (
            id INT AUTO_INCREMENT PRIMARY KEY,
            user_id INT NOT NULL,
            token_hash VARCHAR(64) NOT NULL,
            expires_at DATETIME NOT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
    }
    echo "✓ remember_tokens 表创建完成\n";

    // ---- 3. 尝试创建索引 ----
    try {
        if ($isSqlite) {
            $pdo->exec("CREATE INDEX IF NOT EXISTS idx_remember_token_hash ON remember_tokens(token_hash)");
            $pdo->exec("CREATE INDEX IF NOT EXISTS idx_remember_expires ON remember_tokens(expires_at)");
        } else {
            $pdo->exec("CREATE INDEX idx_remember_token_hash ON remember_tokens(token_hash)");
            $pdo->exec("CREATE INDEX idx_remember_expires ON remember_tokens(expires_at)");
        }
        echo "✓ 索引创建完成\n";
    } catch (PDOException $e) {
        // 索引已存在可忽略
    }

    echo "\n🎉 认证模块数据库迁移完成！\n";
} catch (PDOException $e) {
    die("✗ 迁移失败: " . $e->getMessage() . "\n");
}
