# Real-Time Notification Debug Guide

## Overview
This guide will help you identify why real-time notifications might only update the unread count badge but not display the actual notification content in the dropdown until page refresh.

## Debug Logs Added

### 1. Client-Side (Frontend) Logs

#### **NotificationBell Component** (`client/src/components/NotificationBell.js`)
- **Line 121-122**: Socket connection status check
  ```
  🔔 NotificationBell: Socket status: Connected/Not connected
  🔔 NotificationBell: Socket connected status: true/false
  ```

- **Line 130**: When a new notification is received
  ```
  🔔 NotificationBell: NEW NOTIFICATION RECEIVED: {notification object}
  ```

- **Line 132**: When notifications state is updated
  ```
  🔔 NotificationBell: Updating notifications state, current count: X
  ```

- **Line 136**: When unread count is updated
  ```
  🔔 NotificationBell: Updating unread count from X to Y
  ```

- **Line 146**: When setting up the listener
  ```
  🔔 NotificationBell: Setting up new_notification listener
  ```

#### **Socket Service** (`client/src/services/socket.js`)
- **Line 27**: Socket connection success
  ```
  ✅ Socket.IO: Connected to server {socket.id}
  ```

- **Line 32**: Socket disconnection
  ```
  ❌ Socket.IO: Disconnected from server. Reason: {reason}
  ```

- **Line 37**: Socket connection error
  ```
  ❌ Socket.IO: Connection error: {error}
  ```

### 2. Server-Side (Backend) Logs

#### **Notification Helper** (`utils/notificationHelper.js`)
- **Line 46-51**: When emitting a notification
  ```
  📢 Emitting notification to room: user-{userId}
     Notification ID: {_id}
     Title: {title}
     Type: {type}
     User Type: {userType}
     Full notification object: {JSON}
  ✅ Notification emitted successfully to user-{userId}
  ```

- **Line 56**: If Socket.IO is not available
  ```
  ⚠️ Socket.IO instance not available, notification NOT emitted to user-{userId}
  ```

#### **Server Socket Connection** (`server.js`)
- **Line 322**: User joins notification room
  ```
  ✅ User {userId} joined room: user-{userId}
  ```

- **Line 137-160**: Socket authentication logs
  ```
  🔐 Socket authentication attempt
     Token received: Yes/No
     Verifying JWT token...
  ✅ Token verified successfully
     User ID: {userId}
     User Type: {userType}
  ```

## How to Test Real-Time Notifications

### Step 1: Open Browser Console
1. Open your application in the browser
2. Open Developer Tools (F12)
3. Go to the Console tab
4. Clear the console for a clean slate

### Step 2: Trigger a Notification
Choose one of these actions to trigger a notification:

#### Option A: Schedule a Class (Admin Portal)
1. Log in to the admin portal
2. Go to Class Scheduler
3. Schedule a new class for a student and teacher
4. **Watch Console**: Should see:
   ```
   📢 Emitting notification to room: user-{studentId}
   ✅ Notification emitted successfully to user-{studentId}
   📢 Emitting notification to room: user-{teacherId}
   ✅ Notification emitted successfully to user-{teacherId}
   ```

#### Option B: Submit a QuickTest (Student Portal)
1. Log in to the student portal
2. Go to Quick Test
3. Take and submit a test
4. **Watch Console**: Should see notification emitted to teacher

#### Option C: Delete a Class (Admin Portal)
1. Log in to the admin portal
2. Go to Classes
3. Delete an existing class
4. **Watch Console**: Should see notifications emitted to both student and teacher

### Step 3: Check Client-Side Logs (Student/Teacher Portal)
In the student or teacher portal (whoever should receive the notification):

1. **Check Socket Connection**:
   ```
   ✅ Socket.IO: Connected to server {socket.id}
   🔔 NotificationBell: Socket status: Connected
   🔔 NotificationBell: Socket connected status: true
   🔔 NotificationBell: Setting up new_notification listener
   ```

2. **When Notification Arrives** (should appear automatically):
   ```
   🔔 NotificationBell: NEW NOTIFICATION RECEIVED: {notification}
   🔔 NotificationBell: Updating notifications state, current count: X
   🔔 NotificationBell: Updating unread count from X to Y
   ```

### Step 4: Verify UI Update
- The notification badge count should increase
- The notification bell icon should change to animated icon
- **Most importantly**: Click the bell icon - the notification should appear in the dropdown WITHOUT page refresh

## Common Issues and Solutions

### Issue 1: Socket Not Connected
**Symptoms**:
```
🔔 NotificationBell: Socket status: Not connected
⚠️ NotificationBell: Socket not available, cannot listen for notifications
```

**Causes**:
1. User is not authenticated
2. Socket connection failed
3. Token is invalid

**Solution**:
- Check that user is logged in
- Verify token in localStorage: `localStorage.getItem('{portal}_token')`
- Check server logs for socket authentication errors

### Issue 2: Notification Emitted But Not Received
**Symptoms**:
- Server shows: `✅ Notification emitted successfully to user-{userId}`
- Client shows: No "NEW NOTIFICATION RECEIVED" log

**Possible Causes**:
1. **User ID mismatch**: The userId in the room name doesn't match the logged-in user
2. **Socket disconnected**: User's socket disconnected before notification was sent
3. **Multiple browser tabs**: Socket might be connected in a different tab

**Debug Steps**:
1. Check server log - what userId is the notification being sent to?
   ```
   📢 Emitting notification to room: user-{userId}
   ```

2. Check client - what userId is the user logged in as?
   ```javascript
   // In browser console
   const user = JSON.parse(localStorage.getItem('{portal}_user'));
   console.log('Logged in user ID:', user._id);
   ```

3. Verify socket room membership in server logs:
   ```
   ✅ User {userId} joined room: user-{userId}
   ```

### Issue 3: Notification Received But UI Not Updating
**Symptoms**:
- Client shows: `🔔 NotificationBell: NEW NOTIFICATION RECEIVED`
- Client shows: `🔔 NotificationBell: Updating notifications state`
- But dropdown doesn't show the new notification

**Possible Causes**:
1. React state update not triggering re-render
2. Notification object structure mismatch
3. Component unmounted/remounted

**Debug Steps**:
1. Check the notification object structure in console
2. Verify the notification matches the expected format
3. Try opening the dropdown - does it appear after opening?
4. Check React DevTools to see if state is updating

### Issue 4: Socket.IO Not Available on Server
**Symptoms**:
```
⚠️ Socket.IO instance not available, notification NOT emitted to user-{userId}
```

**Causes**:
- The `io` instance is not being passed to the notification helper
- Express app.get('io') returning undefined

**Solution**:
- Verify in the route handler that `io` is being retrieved:
  ```javascript
  const io = req.app.get('io');
  console.log('IO instance:', io ? 'Available' : 'Not available');
  ```

## Technical Flow

### Complete Notification Flow:
1. **Action Triggered** (e.g., admin schedules class)
2. **Backend Creates Notification** (`utils/notificationHelper.js`)
   - Saves to MongoDB
   - Gets Socket.IO instance
   - Emits to room `user-{userId}`
3. **Server Broadcasts** (`server.js`)
   - Socket.IO emits 'new_notification' event to all sockets in room
4. **Client Receives** (`client/src/components/NotificationBell.js`)
   - Socket listener catches 'new_notification' event
   - Updates React state (notifications array + unread count)
5. **UI Updates** (React re-renders)
   - Badge shows new count
   - Dropdown contains new notification
   - Bell icon animates

## Next Steps After Testing

1. **If logs show notification is emitted but not received**:
   - Problem is with Socket.IO connection or room management
   - Check userId format (ObjectId vs string)
   - Verify socket is still connected when notification is sent

2. **If logs show notification is received but UI doesn't update**:
   - Problem is with React state management
   - Check notification object structure
   - Verify NotificationBell component is mounted

3. **If no logs appear at all**:
   - Check that you're looking at the correct portal
   - Verify action actually triggers notification (check route handler)
   - Clear browser cache and reload

## Remove Debug Logs Later
Once the issue is identified and fixed, you can remove the verbose logging by:
1. Keeping only error/warning logs
2. Removing the detailed console.log statements
3. Optionally keeping a single log for each major event in production

---
**Note**: All timestamps in logs are in UTC. Socket IDs are unique per connection.
