<?php
require_once __DIR__ . '/config/database.php';

try {
    echo "--- Retrying Migration ---\n";
    
    // Check if column exists
    $stmt = $pdo->query("PRAGMA table_info(users)");
    $cols = $stmt->fetchAll(PDO::FETCH_COLUMN, 1);
    
    if (!in_array('wallet_address', $cols)) {
        // Add column WITHOUT Unique constraint first
        $pdo->exec("ALTER TABLE users ADD COLUMN wallet_address TEXT");
        echo "Added wallet_address column (no unique constraint).\n";
        
        // Populate
        $users = $pdo->query("SELECT id FROM users WHERE wallet_address IS NULL")->fetchAll(PDO::FETCH_ASSOC);
        $stmt = $pdo->prepare("UPDATE users SET wallet_address = ? WHERE id = ?");
        
        foreach ($users as $user) {
            $walletAddr = '0x' . bin2hex(random_bytes(20));
            $stmt->execute([$walletAddr, $user['id']]);
        }
        echo "Generated addresses for " . count($users) . " users.\n";
        
        // Create Unique Index
        $pdo->exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_users_wallet_address ON users(wallet_address)");
        echo "Created UNIQUE INDEX on wallet_address.\n";
    } else {
        echo "wallet_address column already exists.\n";
    }

} catch (PDOException $e) {
    echo "Migration Error: " . $e->getMessage() . "\n";
}
