# Join/Leave Group API Documentation

## 🎯 Overview
This API allows users to join and leave groups by adding/removing their details from the group's members array.

## 📋 Endpoints

### **🔗 Join Group**
```bash
POST /api/groups/:groupId/join
```

**Description**: Adds a user to a group's members array with their details.

**Request Body**:
```json
{
  "userId": "68c7ef413c86477b3b626172",
  "role": "member"
}
```

**Parameters**:
- `groupId` (URL param): Group ID to join
- `userId` (body): User ID to add to the group
- `role` (body, optional): User role in the group (`member`, `admin`, `moderator`). Default: `member`

### **🚪 Leave Group**
```bash
POST /api/groups/:groupId/leave
```

**Description**: Removes a user from a group's members array.

**Request Body**:
```json
{
  "userId": "68c7ef413c86477b3b626172"
}
```

**Parameters**:
- `groupId` (URL param): Group ID to leave
- `userId` (body): User ID to remove from the group

## 📊 Response Formats

### **✅ Join Group Success Response (200)**
```json
{
  "success": true,
  "message": "User successfully joined the group",
  "data": {
    "group": {
      "groupId": "68d2a1ec52d4291170859da5",
      "groupName": "Modern Convent School - 2023-24",
      "groupType": "school",
      "description": "Group for students of Modern Convent School",
      "memberCount": 26,
      "membersCount": 26,
      "isActive": true,
      "createdBy": {
        "userId": "68c7ef413c86477b3b626172",
        "name": "John Doe",
        "mobile": "9876543210"
      },
      "schoolId": "MODERN_CONVENT_SCHOOL_2023-24",
      "collegeId": null,
      "createdAt": "2025-01-22T10:30:00.000Z",
      "updatedAt": "2025-01-22T14:00:00.000Z"
    },
    "user": {
      "userId": "68c7ef413c86477b3b626173",
      "name": "Jane Smith",
      "mobile": "9876543211",
      "role": "member",
      "joinDate": "2025-01-22T14:00:00.000Z",
      "isActive": true
    },
    "membership": {
      "totalMembers": 26,
      "userPosition": 26,
      "role": "member"
    }
  }
}
```

### **✅ Already Member Response (200)**
```json
{
  "success": true,
  "message": "User is already a member of this group",
  "data": {
    "group": {
      "groupId": "68d2a1ec52d4291170859da5",
      "groupName": "Modern Convent School - 2023-24",
      "groupType": "school",
      "memberCount": 25,
      "membersCount": 25
    },
    "user": {
      "userId": "68c7ef413c86477b3b626173",
      "name": "Jane Smith",
      "mobile": "9876543211",
      "role": "member",
      "joinDate": "2025-01-22T10:30:00.000Z",
      "isActive": true
    },
    "alreadyMember": true
  }
}
```

### **✅ Leave Group Success Response (200)**
```json
{
  "success": true,
  "message": "User successfully left the group",
  "data": {
    "group": {
      "groupId": "68d2a1ec52d4291170859da5",
      "groupName": "Modern Convent School - 2023-24",
      "groupType": "school",
      "memberCount": 24,
      "membersCount": 24
    },
    "user": {
      "userId": "68c7ef413c86477b3b626173",
      "name": "Jane Smith",
      "mobile": "9876543211"
    },
    "membership": {
      "totalMembers": 24,
      "removedRole": "member",
      "removedJoinDate": "2025-01-22T10:30:00.000Z"
    }
  }
}
```

## ❌ Error Responses

### **400 Bad Request**
```json
{
  "success": false,
  "message": "User ID is required"
}
```

### **404 Not Found (User)**
```json
{
  "success": false,
  "message": "User not found"
}
```

### **404 Not Found (Group)**
```json
{
  "success": false,
  "message": "Group not found"
}
```

### **400 Bad Request (Group Inactive)**
```json
{
  "success": false,
  "message": "Group is not active"
}
```

### **400 Bad Request (Not a Member)**
```json
{
  "success": false,
  "message": "User is not a member of this group"
}
```

### **500 Server Error**
```json
{
  "success": false,
  "message": "Failed to join group",
  "error": "Database connection error"
}
```

## 🔍 Key Features

### **✅ Smart Member Detection**
- Checks if user is already a member before adding
- Returns appropriate response for existing members
- Prevents duplicate memberships

### **✅ Role Management**
- Supports different roles: `member`, `admin`, `moderator`
- Default role is `member`
- Role is stored with user details in members array

### **✅ Member Count Updates**
- Automatically updates `memberCount` in Group model
- Synchronizes with actual members array length
- Provides accurate member statistics

### **✅ Comprehensive Validation**
- Validates user existence
- Validates group existence
- Checks group active status
- Validates membership status for leave operations

### **✅ Detailed Responses**
- Returns complete group information
- Includes user details and membership info
- Provides membership statistics

## 🧪 Usage Examples

### **JavaScript/Axios**
```javascript
// Join a group
const joinResponse = await axios.post('/api/groups/68d2a1ec52d4291170859da5/join', {
  userId: '68c7ef413c86477b3b626173',
  role: 'member'
});

// Leave a group
const leaveResponse = await axios.post('/api/groups/68d2a1ec52d4291170859da5/leave', {
  userId: '68c7ef413c86477b3b626173'
});

// Check user's groups and membership status
const userGroups = await axios.get('/api/groups/user/68c7ef413c86477b3b626173');
```

### **Flutter/Dart**
```dart
// Join a group
final joinResponse = await http.post(
  Uri.parse('$baseUrl/api/groups/68d2a1ec52d4291170859da5/join'),
  headers: {'Content-Type': 'application/json'},
  body: json.encode({
    'userId': '68c7ef413c86477b3b626173',
    'role': 'member'
  }),
);

// Leave a group
final leaveResponse = await http.post(
  Uri.parse('$baseUrl/api/groups/68d2a1ec52d4291170859da5/leave'),
  headers: {'Content-Type': 'application/json'},
  body: json.encode({
    'userId': '68c7ef413c86477b3b626173'
  }),
);
```

### **cURL Examples**
```bash
# Join a group
curl -X POST "http://localhost:5500/api/groups/68d2a1ec52d4291170859da5/join" \
  -H "Content-Type: application/json" \
  -d '{"userId":"68c7ef413c86477b3b626173","role":"member"}'

# Leave a group
curl -X POST "http://localhost:5500/api/groups/68d2a1ec52d4291170859da5/leave" \
  -H "Content-Type: application/json" \
  -d '{"userId":"68c7ef413c86477b3b626173"}'
```

## 🔄 Integration with Existing APIs

### **Get User Groups**
After joining/leaving groups, use the existing endpoint to check membership status:
```bash
GET /api/groups/user/:userId
```

This will show:
- `isUserMember`: Whether user is in the members array
- `memberCount`: Total members in the group
- `membersCount`: Actual members array length

### **Group Details**
Get complete group information including all members:
```bash
GET /api/groups/:groupId
```

## 🧪 Testing

Run the test script to verify functionality:
```bash
node scripts/testJoinLeaveGroupAPI.js
```

The test script covers:
- ✅ Join group functionality
- ✅ Leave group functionality
- ✅ Already member detection
- ✅ Membership status checking
- ✅ Error scenarios
- ✅ Invalid user/group handling

## 📝 Notes

1. **No Authentication Required**: These endpoints are public for flexibility
2. **User Details**: User name and mobile are automatically fetched and stored
3. **Join Date**: Automatically set when user joins
4. **Member Count**: Automatically maintained and synchronized
5. **Role Support**: Flexible role system for group management
6. **Comprehensive Logging**: All operations are logged for debugging

## 🎯 Use Cases

- **School Groups**: Students joining their class/school groups
- **College Groups**: Students joining course/department groups
- **Professional Groups**: Professionals joining industry/company groups
- **Community Groups**: General interest-based group memberships
- **Event Groups**: Temporary groups for events or activities

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