#!/bin/bash
# Token Versioning Setup Script

echo "========================================="
echo "Token Versioning Setup"
echo "========================================="
echo ""

# Check if .env or config exists for DB credentials
if [ ! -f "config/config.php" ]; then
    echo "❌ Error: config/config.php not found"
    echo "Please ensure database configuration exists"
    exit 1
fi

echo "📋 This script will:"
echo "  1. Add tokenVersion column to users table"
echo "  2. Initialize all existing users with tokenVersion = 0"
echo "  3. Create an index for performance"
echo ""

read -p "Do you want to continue? (y/n): " -n 1 -r
echo ""

if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo "❌ Setup cancelled"
    exit 1
fi

echo ""
echo "📦 Running migration..."
echo ""

# Get database credentials from user
read -p "Enter MySQL username: " DB_USER
read -sp "Enter MySQL password: " DB_PASS
echo ""
read -p "Enter database name: " DB_NAME

# Run the migration
mysql -u "$DB_USER" -p"$DB_PASS" "$DB_NAME" < migrations/add_token_version.sql

if [ $? -eq 0 ]; then
    echo ""
    echo "✅ Migration completed successfully!"
    echo ""
    echo "📝 Next steps:"
    echo "  1. Deploy updated PHP files to your server:"
    echo "     - /auth/email-login.php"
    echo "     - /auth/social-login.php"
    echo "     - /middleware/auth.php"
    echo ""
    echo "  2. Clear server cache:"
    echo "     Visit: https://your-domain/api/clear-cache.php"
    echo ""
    echo "  3. Restart PHP-FPM:"
    echo "     sudo systemctl restart php-fpm"
    echo ""
    echo "  4. Test the implementation (see TOKEN_VERSIONING.md)"
    echo ""
else
    echo ""
    echo "❌ Migration failed!"
    echo "Please check:"
    echo "  - Database credentials are correct"
    echo "  - Database exists and is accessible"
    echo "  - MySQL user has ALTER TABLE privileges"
    echo ""
    exit 1
fi
