# Groups by User ID API Documentation

## Available Endpoints

There are **two main endpoints** for fetching groups by user ID:

### 1. Primary Endpoint (Recommended)
```
GET /api/groups/user/:userId
```

### 2. Alternative Endpoint
```
GET /api/groups/user/:userId/groups
```

## Endpoint 1: GET /api/groups/user/:userId

### Description
Retrieves all groups associated with a specific user by checking the user's group IDs (schoolGroupId, collegeGroupId, professionalGroupId).

### Parameters
- `userId` (required): The ID of the user whose groups you want to retrieve
  - Type: String
  - Format: MongoDB ObjectId (24 character hex string)
  - Example: `68c7ef413c86477b3b626172`

### Authentication
- **Required**: No authentication required
- **Public Route**: This endpoint is publicly accessible

### Request Examples

#### Basic Request
```bash
GET /api/groups/user/68c7ef413c86477b3b626172
```

#### JavaScript/Axios
```javascript
const response = await axios.get('/api/groups/user/68c7ef413c86477b3b626172');
```

#### Flutter/Dart
```dart
final response = await http.get(
  Uri.parse('$baseUrl/api/groups/user/68c7ef413c86477b3b626172'),
  headers: {
    'Content-Type': 'application/json',
  },
);
```

### Response Format

#### Success Response (200)
```json
{
  "success": true,
  "message": "User groups retrieved successfully",
  "data": {
    "user": {
      "userId": "68c7ef413c86477b3b626172",
      "name": "John Doe",
      "mobile": "9515446080"
    },
    "groups": [
      {
        "groupId": "68d2a1ec52d4291170859da5",
        "groupType": "school",
        "groupName": "AP MODEL SCHOOL VAVILAPALLIPETA - 2018",
        "description": "School group for AP MODEL SCHOOL VAVILAPALLIPETA (2018)",
        "memberCount": 5,
        "membersCount": 5,
        "isActive": true,
        "createdAt": "2025-01-22T14:00:18.204Z",
        "updatedAt": "2025-01-22T14:00:18.204Z"
      },
      {
        "groupId": "68d2a1ec52d4291170859da6",
        "groupType": "college",
        "groupName": "A.A. Government Arts College - Bachelor of Computer Science",
        "description": "College group for A.A. Government Arts College (Bachelor of Computer Science - Computer Science and Engineering)",
        "memberCount": 3,
        "membersCount": 3,
        "isActive": true,
        "createdAt": "2025-01-22T14:05:18.204Z",
        "updatedAt": "2025-01-22T14:05:18.204Z"
      }
    ],
    "totalGroups": 2
  }
}
```

#### Empty Response (No Groups Found)
```json
{
  "success": true,
  "message": "No groups found for user",
  "data": {
    "user": {
      "userId": "68c7ef413c86477b3b626172",
      "name": "John Doe",
      "mobile": "9515446080"
    },
    "groups": [],
    "totalGroups": 0
  }
}
```

#### Error Responses

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

##### Server Error (500)
```json
{
  "success": false,
  "message": "Failed to get user groups",
  "error": "Error message details"
}
```

## Endpoint 2: GET /api/groups/user/:userId/groups

### Description
Alternative endpoint that retrieves groups where the user is the creator/owner.

### Parameters
- `userId` (required): The ID of the user whose groups you want to retrieve
- `groupType` (optional): Filter by group type (school, college, professional)

### Query Parameters
- `groupType` (optional): Filter by specific group type
  - Values: `school`, `college`, `professional`
  - Example: `?groupType=school`

### Request Examples

#### Basic Request
```bash
GET /api/groups/user/68c7ef413c86477b3b626172/groups
```

#### With Group Type Filter
```bash
GET /api/groups/user/68c7ef413c86477b3b626172/groups?groupType=school
```

#### JavaScript/Axios
```javascript
const response = await axios.get('/api/groups/user/68c7ef413c86477b3b626172/groups');
```

### Response Format

#### Success Response (200)
```json
{
  "success": true,
  "message": "User groups retrieved successfully",
  "data": {
    "groups": [
      {
        "_id": "68d2a1ec52d4291170859da5",
        "groupType": "school",
        "userId": "68c7ef413c86477b3b626172",
        "schoolId": "28110900905_2018",
        "groupName": "AP MODEL SCHOOL VAVILAPALLIPETA - 2018",
        "description": "School group for AP MODEL SCHOOL VAVILAPALLIPETA (2018)",
        "memberCount": 5,
        "members": [
          {
            "user_id": "68c7ef413c86477b3b626172",
            "name": "AP MODEL SCHOOL VAVILAPALLIPETA",
            "joinDate": "2025-01-22T14:00:18.204Z",
            "role": "admin",
            "isActive": true
          }
        ],
        "isActive": true,
        "createdAt": "2025-01-22T14:00:18.204Z",
        "updatedAt": "2025-01-22T14:00:18.204Z"
      }
    ],
    "totalGroups": 1
  }
}
```

## Related Group Endpoints

### Get All Groups
```bash
GET /api/groups
```

### Get Group by ID
```bash
GET /api/groups/:groupId
```

### Get Group by School ID
```bash
GET /api/groups/school/:schoolId
```

### Get Group by College ID
```bash
GET /api/groups/college/:collegeId
```

### Create Group (Protected)
```bash
POST /api/groups
Authorization: Bearer <token>
```

### Update Group (Protected)
```bash
PUT /api/groups/:groupId
Authorization: Bearer <token>
```

### Delete Group (Protected)
```bash
DELETE /api/groups/:groupId
Authorization: Bearer <token>
```

## Response Fields

### Group Object
- `groupId` or `_id`: Unique identifier for the group
- `groupType`: Type of group (school, college, professional)
- `groupName`: Name of the group
- `description`: Description of the group
- `memberCount`: Total number of members
- `membersCount`: Count of members in the members array
- `members`: Array of member objects (detailed view)
  - `user_id`: User ID of the member
  - `name`: Name of the member
  - `joinDate`: Date when the member joined
  - `role`: Role of the member (admin, member, moderator)
  - `isActive`: Whether the member is active
- `isActive`: Whether the group is active
- `createdAt`: Creation timestamp
- `updatedAt`: Last update timestamp

### User Object (in response)
- `userId` or `_id`: User ID
- `name`: User's name
- `mobile`: User's mobile number

## Key Differences Between Endpoints

### Endpoint 1: `/api/groups/user/:userId`
- **Purpose**: Gets groups the user is **associated with** (member of)
- **Method**: Checks user's group IDs (schoolGroupId, collegeGroupId, professionalGroupId)
- **Use Case**: When you want to show all groups a user belongs to
- **Response**: Simplified group information with user details

### Endpoint 2: `/api/groups/user/:userId/groups`
- **Purpose**: Gets groups the user **created/owns**
- **Method**: Finds groups where userId matches the creator
- **Use Case**: When you want to show groups a user has created
- **Response**: Full group information with members array

## Usage Examples

### Get User's Associated Groups (Recommended)
```bash
GET /api/groups/user/68c7ef413c86477b3b626172
```

### Get User's Created Groups
```bash
GET /api/groups/user/68c7ef413c86477b3b626172/groups
```

### Get User's School Groups Only
```bash
GET /api/groups/user/68c7ef413c86477b3b626172/groups?groupType=school
```

### Get User's College Groups Only
```bash
GET /api/groups/user/68c7ef413c86477b3b626172/groups?groupType=college
```

## Testing

Run the test script to verify the endpoints:
```bash
node scripts/testGroupMembersAPI.js
```

## Notes

- Both endpoints are publicly accessible (no authentication required)
- Endpoint 1 is recommended for most use cases
- Endpoint 2 provides more detailed group information
- Groups are sorted by creation date (newest first)
- Only active groups are returned (isActive: true)
- Empty arrays are returned for users with no groups (not an error)
