# Demo Join Group API

## 🎯 Simple Demo API for Frontend

This is a simplified API that takes only `userId` and `groupId` from the frontend and handles everything in the backend, including fetching user details and creating the exact member object structure that the Group model expects.

## 📋 Endpoint

```bash
POST /api/groups/demo/join
```

## 📝 Request Body

```json
{
  "userId": "68c7ef413c86477b3b626172",
  "groupId": "68d2a1ec52d4291170859da5"
}
```

**Required Fields:**
- `userId`: User ID to add to the group
- `groupId`: Group ID to join

## 📊 Response Format

### ✅ 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,
      "schoolId": "MODERN_CONVENT_SCHOOL_2023-24",
      "collegeId": null,
      "createdAt": "2025-01-22T10:30:00.000Z",
      "updatedAt": "2025-01-22T14:00:00.000Z"
    },
    "user": {
      "userId": "68c7ef413c86477b3b626172",
      "name": "John Doe",
      "mobile": "9876543210",
      "emailId": "john@example.com",
      "occupation": "school student",
      "role": "member",
      "joinDate": "2025-01-22T14:00:00.000Z",
      "isActive": true
    },
    "membership": {
      "totalMembers": 26,
      "userPosition": 26,
      "role": "member",
      "joinDate": "2025-01-22T14:00:00.000Z"
    }
  }
}
```

### ✅ 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,
      "schoolId": "MODERN_CONVENT_SCHOOL_2023-24",
      "collegeId": null
    },
    "user": {
      "userId": "68c7ef413c86477b3b626172",
      "name": "John Doe",
      "mobile": "9876543210",
      "emailId": "john@example.com",
      "occupation": "school student",
      "role": "member",
      "joinDate": "2025-01-22T10:30:00.000Z",
      "isActive": true
    },
    "alreadyMember": true
  }
}
```

## ❌ Error Responses

### 400 Bad Request
```json
{
  "success": false,
  "message": "User ID and Group ID are 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"
}
```

## 🔍 What the Backend Does

1. **Validates Input**: Checks if `userId` and `groupId` are provided
2. **Fetches User Details**: Gets user information from User model (name, mobile, emailId, occupation)
3. **Fetches Group Details**: Gets group information from Group model
4. **Validates Group**: Checks if group exists and is active
5. **Checks Membership**: Verifies if user is already a member
6. **Creates Member Object**: Builds the exact structure expected by Group model:
   ```javascript
   {
     user_id: userId,        // ObjectId reference to User
     name: user.name,        // User's name from User model
     joinDate: new Date(),   // Current timestamp
     role: 'member',         // Default role
     isActive: true          // Active status
   }
   ```
7. **Updates Group**: Adds member to members array and updates memberCount
8. **Returns Response**: Provides complete group and user information

## 🧪 Usage Examples

### JavaScript/Axios
```javascript
const response = await axios.post('/api/groups/demo/join', {
  userId: '68c7ef413c86477b3b626172',
  groupId: '68d2a1ec52d4291170859da5'
});
```

### Flutter/Dart
```dart
final response = await http.post(
  Uri.parse('$baseUrl/api/groups/demo/join'),
  headers: {'Content-Type': 'application/json'},
  body: json.encode({
    'userId': '68c7ef413c86477b3b626172',
    'groupId': '68d2a1ec52d4291170859da5'
  }),
);
```

### cURL
```bash
curl -X POST "http://localhost:5500/api/groups/demo/join" \
  -H "Content-Type: application/json" \
  -d '{"userId":"68c7ef413c86477b3b626172","groupId":"68d2a1ec52d4291170859da5"}'
```

## 🧪 Testing

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

## 📝 Key Features

- ✅ **Simple Input**: Only requires userId and groupId
- ✅ **Automatic Data Fetching**: Backend fetches all user details
- ✅ **Exact Model Structure**: Creates member object exactly as Group model expects
- ✅ **Duplicate Prevention**: Checks if user is already a member
- ✅ **Complete Response**: Returns full group and user information
- ✅ **Error Handling**: Proper validation and error responses
- ✅ **No Authentication Required**: Public endpoint for easy testing

## 🎯 Perfect for Frontend

This API is designed specifically for frontend integration where you only need to send:
1. `userId` - The user who wants to join
2. `groupId` - The group to join

The backend handles everything else automatically! 🎯✅
