# Google OAuth Registration Fix Plan

## Problem Analysis

### Issue: Users Cannot Re-Register After Deletion
When a user is deleted from admin panel and tries to re-register with Google, they get:
**"حدث خطأ في التحقق من Google"** (Google verification error)

### Root Causes Identified:

1. **Email Prefix on Deletion**: When deleting users, email is prefixed (e.g., `deleted_8_email@gmail.com`)
2. **Google ID Conflict**: If the deleted user had a `google_id`, it might still exist in database
3. **Unique Constraint Violation**: When creating new user with same Google email, database might reject it
4. **Token Exchange Failure**: The `fetch_token()` might be failing due to redirect URI mismatch

### Current Callback Flow Issues:

```
User clicks "التسجيل بحساب Google"
↓
Redirects to Google OAuth
↓
Google redirects back to /auth/google/callback
↓
Callback tries to exchange code for tokens
↓
If fetch_token fails → Generic error message
↓
Redirects to /auth/login with error
```

---

## Implementation Plan

### Step 1: Fix User Deletion to Properly Clean Google Data

**File:** `app/routes/admin.py` - `delete_user()` function

When deleting a user, also clear their Google OAuth data:

```python
@admin_bp.route("/users/<int:user_id>/delete", methods=["POST"])
@admin_required
def delete_user(user_id):
    from datetime import datetime
    user = User.query.get_or_404(user_id)
    if user.id == current_user.id:
        flash("لا يمكنك حذف حسابك الخاص.", "error")
        return redirect(url_for("admin.users"))

    reason = request.form.get("reason", "").strip() or "لم يتم تحديد السبب"

    # Store original email before deletion for reference
    original_email = user.email
    original_google_id = user.google_id

    user.deleted_at = datetime.utcnow()
    user.deleted_by_id = current_user.id
    user.is_active = False

    # Prefix email to free it up for re-registration
    user.email = f"deleted_{user.id}_{original_email}"

    # Clear Google OAuth data to allow re-registration
    user.google_id = None
    user.google_email = None
    user.google_access_token = None
    user.google_refresh_token = None
    user.auth_provider = 'email' if user.password_hash else None

    db.session.commit()

    flash(f"تم حذف حساب {user.name}. السبب: {reason}", "success")
    return redirect(url_for("admin.users"))
```

### Step 2: Improve Error Logging in OAuth Callback

**File:** `app/routes/auth.py` - `google_callback()` function

Add more detailed error logging:

```python
@auth_bp.route("/google/callback")
@limiter.limit("20 per hour")
def google_callback():
    """Handle Google OAuth callback."""
    from flask import session, current_app, request as req
    from app.auth.google_oauth import GoogleOAuth

    oauth = GoogleOAuth()

    current_app.logger.info(f"Google callback received: {req.url}")
    current_app.logger.info(f"Request method: {req.method}")
    current_app.logger.info(f"Request args: {dict(req.args)}")

    # Handle OAuth error
    if 'error' in req.args:
        error = req.args.get('error')
        error_description = req.args.get('error_description', '')
        current_app.logger.error(f"Google OAuth error: {error} - {error_description}")
        flash(f"حدث خطأ أثناء تسجيل الدخول عبر Google: {error}", "error")
        return redirect(url_for('auth.login'))

    # Check if we have an authorization code
    code = req.args.get('code')
    if not code:
        current_app.logger.error("No authorization code in callback")
        flash("حدث خطأ في التحقق من Google - لا يوجد رمز تفويض", "error")
        return redirect(url_for('auth.login'))

    # Exchange authorization code for tokens
    try:
        current_app.logger.info("Attempting to fetch token...")
        credentials = oauth.fetch_token(req.url)
        current_app.logger.info(f"Token fetched successfully")

        if 'token' not in credentials:
            current_app.logger.error(f"No token in credentials: {list(credentials.keys())}")
            flash("حدث خطأ في التحقق من Google - لم يتم الحصول على رمز", "error")
            return redirect(url_for('auth.login'))

        user_info = oauth.get_user_info(credentials)
        current_app.logger.info(f"User info retrieved: {user_info.get('email', 'no-email')}")
    except ValueError as e:
        current_app.logger.error(f"Google OAuth ValueError: {e}")
        import traceback
        current_app.logger.error(traceback.format_exc())
        flash(f"حدث خطأ في التحقق من Google: {str(e)}", "error")
        return redirect(url_for('auth.login'))
    except Exception as e:
        current_app.logger.error(f"Google OAuth error: {e}")
        import traceback
        current_app.logger.error(traceback.format_exc())
        flash(f"حدث خطأ في التحقق من Google: {str(e)}", "error")
        return redirect(url_for('auth.login'))

    # ... rest of the code
```

### Step 3: Handle Existing Deleted Users on Callback

**File:** `app/routes/auth.py` - `google_callback()` function

When checking for existing users, also check for deleted users and clean them up:

```python
# Check if user already exists with this Google ID
from app.models.user import User
user = User.query.filter_by(google_id=user_info['google_id']).first()

# If no user found with google_id, check if email exists for a deleted user
if not user:
    deleted_user = User.query.filter(
        User.email.like(f"%{user_info['email']}%"),
        User.deleted_at.isnot(None)
    ).first()

    if deleted_user:
        # Permanently delete the old deleted user and allow re-registration
        current_app.logger.info(f"Found deleted user with same email, cleaning up: {deleted_user.id}")
        db.session.delete(deleted_user)
        db.session.commit()
        user = None

if user:
    # Existing user - update tokens and log in
    # ... existing code ...
```

### Step 4: Fix Redirect URI Mismatch (If Needed)

**File:** Check `.env` for correct redirect URI

The redirect URI in Google Cloud Console must match exactly:
- `https://jadwaai.com/auth/google/callback`

### Step 5: Add Better Error Messages

**File:** `app/templates/auth/login.html`

Add a debug section to show OAuth errors more clearly:

```html
{% with messages = get_flashed_messages(with_categories=true) %}
    {% if messages %}
        {% for category, message in messages %}
        <div class="mb-4 p-4 rounded-xl {% if category == 'error' %}bg-red-500/20 border-red-500/50{% else %}bg-emerald-500/20 border-emerald-500/50{% endif %} text-sm text-white">
            {{ message }}
            {% if category == 'error' %}
            <br><small class="text-slate-400 mt-2 block">إذا استمرت المشكلة، تواصل مع الدعم الفني.</small>
            {% endif %}
        </div>
        {% endfor %}
    {% endif %}
{% endwith %}
```

---

## Implementation Steps

### Step 1: Update User Deletion
Modify `app/routes/admin.py` to clear Google data on deletion

### Step 2: Update Google Callback
Add deleted user cleanup and better error logging

### Step 3: Test the Flow
1. Delete user ashraffaridhdd@gmail.com
2. Try to register again with Google
3. Should work without errors

---

## Files to Modify

1. **`app/routes/admin.py`** - `delete_user()` function
2. **`app/routes/auth.py`** - `google_callback()` function
3. **`app/templates/auth/login.html`** - Better error display

---

## Expected Result After Fix

1. User deleted from admin panel → Google data cleared
2. User tries to register with Google → No conflicts
3. OAuth callback succeeds → New account created
4. User logged in successfully
