# Group Chat API Documentation

## 🎯 Overview
Complete group chat system with real-time messaging, file uploads, and WebSocket support.

## 📋 API Endpoints

### **1. Get Complete Group Details**
```bash
GET /api/groups/:groupId
GET /api/groups/:groupId?includeMessages=true&messageLimit=10
```

**Response includes:**
- Complete group information
- All members with user details (name, mobile, email, profileImage, occupation)
- Member roles and join dates
- Group statistics (admin count, moderator count, etc.)
- Recent messages (optional)

### **2. Group Messages**

#### **Get Recent Messages**
```bash
GET /api/groups/:groupId/messages?limit=500&offset=0
```

#### **Send Message**
```bash
POST /api/groups/:groupId/send
Content-Type: application/json

{
  "userId": "68c7ef413c86477b3b626172",
  "message": "Hello everyone!",
  "messageType": "text",
  "replyTo": "optional_message_id"
}
```

#### **Send Media Message**
```bash
POST /api/groups/:groupId/send
Content-Type: multipart/form-data

Form Data:
- userId: "68c7ef413c86477b3b626172"
- message: "Check this out!"
- messageType: "image"
- media: [file]
```

#### **Search Messages**
```bash
GET /api/groups/:groupId/search?searchTerm=hello&limit=100
```

#### **Edit Message**
```bash
PUT /api/groups/message/:messageId/edit
{
  "userId": "68c7ef413c86477b3b626172",
  "newMessage": "Updated message content"
}
```

#### **Delete Message**
```bash
DELETE /api/groups/message/:messageId
{
  "userId": "68c7ef413c86477b3b626172"
}
```

#### **Add Reaction**
```bash
POST /api/groups/message/:messageId/reaction
{
  "userId": "68c7ef413c86477b3b626172",
  "emoji": "👍"
}
```

## 🔌 WebSocket Real-Time Chat

### **Connection**
```javascript
const ws = new WebSocket('ws://localhost:5500/ws/group-chat?token=<JWT_TOKEN>');
```

### **Message Types**

#### **Join Group**
```javascript
ws.send(JSON.stringify({
  type: 'join_group',
  groupId: '68d2a1ec52d4291170859da5'
}));
```

#### **Send Message**
```javascript
ws.send(JSON.stringify({
  type: 'send_message',
  groupId: '68d2a1ec52d4291170859da5',
  content: 'Hello from WebSocket!',
  messageType: 'text',
  clientMessageId: 'unique_client_id'
}));
```

#### **Typing Indicators**
```javascript
// Start typing
ws.send(JSON.stringify({
  type: 'typing_start',
  groupId: '68d2a1ec52d4291170859da5'
}));

// Stop typing
ws.send(JSON.stringify({
  type: 'typing_stop',
  groupId: '68d2a1ec52d4291170859da5'
}));
```

#### **Leave Group**
```javascript
ws.send(JSON.stringify({
  type: 'leave_group',
  groupId: '68d2a1ec52d4291170859da5'
}));
```

### **WebSocket Response Types**

#### **Connected**
```json
{
  "type": "connected",
  "message": "Connected to group chat",
  "user": {
    "id": "68c7ef413c86477b3b626172",
    "name": "John Doe",
    "mobile": "9876543210",
    "profileImage": "url"
  }
}
```

#### **Joined Group**
```json
{
  "type": "joined_group",
  "groupId": "68d2a1ec52d4291170859da5",
  "groupName": "My School Group",
  "message": "Joined My School Group"
}
```

#### **New Message**
```json
{
  "type": "new_message",
  "message": {
    "_id": "68d2a1ec52d4291170859da6",
    "groupId": "68d2a1ec52d4291170859da5",
    "userId": {
      "_id": "68c7ef413c86477b3b626172",
      "name": "John Doe",
      "mobile": "9876543210",
      "profileImage": "url"
    },
    "message": "Hello everyone!",
    "messageType": "text",
    "createdAt": "2025-01-22T14:00:00.000Z"
  },
  "groupId": "68d2a1ec52d4291170859da5",
  "timestamp": "2025-01-22T14:00:00.000Z"
}
```

#### **User Joined/Left**
```json
{
  "type": "user_joined",
  "user": {
    "id": "68c7ef413c86477b3b626172",
    "name": "John Doe",
    "mobile": "9876543210"
  },
  "groupId": "68d2a1ec52d4291170859da5",
  "timestamp": "2025-01-22T14:00:00.000Z"
}
```

#### **Typing Indicators**
```json
{
  "type": "user_typing_start",
  "user": {
    "id": "68c7ef413c86477b3b626172",
    "name": "John Doe"
  },
  "groupId": "68d2a1ec52d4291170859da5"
}
```

## 📊 Response Examples

### **Complete Group Details Response**
```json
{
  "success": true,
  "message": "Group information retrieved successfully",
  "data": {
    "group": {
      "groupId": "68d2a1ec52d4291170859da5",
      "groupName": "Modern Convent School - 2023-24",
      "groupType": "school",
      "description": "Group for students of Modern Convent School",
      "memberCount": 25,
      "membersCount": 25,
      "isActive": true,
      "createdBy": {
        "userId": "68c7ef413c86477b3b626172",
        "name": "John Doe",
        "mobile": "9876543210",
        "email": "john@example.com",
        "profileImage": "profile_image_url"
      },
      "members": [
        {
          "user_id": "68c7ef413c86477b3b626172",
          "name": "John Doe",
          "joinDate": "2025-01-22T10:30:00.000Z",
          "role": "admin",
          "isActive": true,
          "userDetails": {
            "name": "John Doe",
            "mobile": "9876543210",
            "email": "john@example.com",
            "profileImage": "profile_image_url",
            "occupation": "school student"
          }
        }
      ],
      "schoolId": "MODERN_CONVENT_SCHOOL_2023-24",
      "collegeId": null,
      "recentMessages": [
        {
          "_id": "68d2a1ec52d4291170859da6",
          "message": "Hello everyone!",
          "messageType": "text",
          "userId": {
            "_id": "68c7ef413c86477b3b626172",
            "name": "John Doe",
            "profileImage": "url"
          },
          "createdAt": "2025-01-22T14:00:00.000Z"
        }
      ]
    },
    "statistics": {
      "totalMembers": 25,
      "activeMembers": 24,
      "adminCount": 2,
      "moderatorCount": 3,
      "regularMemberCount": 20,
      "recentMessagesCount": 5
    }
  }
}
```

### **Recent Messages Response**
```json
{
  "success": true,
  "message": "Recent messages retrieved successfully",
  "data": {
    "group": {
      "groupId": "68d2a1ec52d4291170859da5",
      "groupName": "Modern Convent School - 2023-24",
      "groupType": "school",
      "memberCount": 25
    },
    "messages": [
      {
        "_id": "68d2a1ec52d4291170859da6",
        "groupId": "68d2a1ec52d4291170859da5",
        "userId": {
          "_id": "68c7ef413c86477b3b626172",
          "name": "John Doe",
          "mobile": "9876543210",
          "profileImage": "url"
        },
        "message": "Hello everyone!",
        "messageType": "text",
        "isEdited": false,
        "isDeleted": false,
        "reactions": [
          {
            "userId": "68c7ef413c86477b3b626173",
            "emoji": "👍",
            "reactedAt": "2025-01-22T14:05:00.000Z"
          }
        ],
        "createdAt": "2025-01-22T14:00:00.000Z",
        "updatedAt": "2025-01-22T14:00:00.000Z"
      }
    ],
    "pagination": {
      "totalMessages": 150,
      "returnedMessages": 10,
      "limit": 10,
      "offset": 0,
      "hasMore": true
    }
  }
}
```

## 🎯 Key Features

### **✅ Complete Group Details**
- Full member information with user details
- Member roles and statistics
- Optional recent messages
- Group metadata and settings

### **✅ Rich Messaging**
- Text messages
- Image/video/file uploads (up to 100MB)
- Message editing and deletion
- Reactions with emojis
- Reply to messages
- Message search

### **✅ Real-Time WebSocket**
- Live messaging
- Typing indicators
- User join/leave notifications
- Connection management
- Message broadcasting

### **✅ File Management**
- Automatic file upload to `uploads/group_messages/`
- Support for images, videos, documents
- File serving with proper MIME types
- Compression and optimization

### **✅ Security & Validation**
- JWT authentication for WebSocket
- User membership validation
- File type validation
- Message content validation
- Rate limiting and error handling

## 🧪 Testing

Run the comprehensive test script:
```bash
node scripts/testGroupDetailsAndChatAPI.js
```

## 📝 Usage Examples

### **JavaScript/Axios**
```javascript
// Get group details
const groupDetails = await axios.get('/api/groups/68d2a1ec52d4291170859da5');

// Send message
const message = await axios.post('/api/groups/68d2a1ec52d4291170859da5/send', {
  userId: '68c7ef413c86477b3b626172',
  message: 'Hello everyone!',
  messageType: 'text'
});

// Get recent messages
const messages = await axios.get('/api/groups/68d2a1ec52d4291170859da5/messages?limit=50');
```

### **WebSocket Client**
```javascript
const ws = new WebSocket('ws://localhost:5500/ws/group-chat?token=your_jwt_token');

ws.onopen = () => {
  // Join a group
  ws.send(JSON.stringify({
    type: 'join_group',
    groupId: '68d2a1ec52d4291170859da5'
  }));
};

ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  
  switch (data.type) {
    case 'new_message':
      // Display new message
      displayMessage(data.message);
      break;
    case 'user_joined':
      // Show user joined notification
      showNotification(`${data.user.name} joined the group`);
      break;
    // Handle other message types...
  }
};
```

## 🎯 Perfect for Group Chat Applications

This system provides everything needed for a complete group chat experience:
- ✅ Real-time messaging
- ✅ File sharing
- ✅ User management
- ✅ Message history
- ✅ Typing indicators
- ✅ Message reactions
- ✅ Search functionality
- ✅ Mobile-friendly

All APIs are ready to use and fully functional! 🎯✅
