# Communication API Usage Guide

## Get Group Messages When Student Enters Group Chat

### Endpoint
```
GET /api/communication/getGroupMessages
```

### Description
This endpoint retrieves all existing messages from a group chat when a student enters the group. It fetches messages based on the class ID and optional section ID.

### Authentication
Requires authentication token in the request header.

### Query Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `class_id` or `classId` | Number/String | Yes | The class identifier |
| `section_id` or `sectionId` | Number/String | No | The section identifier (defaults to 'all' if not provided) |

### Example Request

```javascript
// Using fetch
const response = await fetch(
  'http://your-server/api/communication/getGroupMessages?class_id=10&section_id=A',
  {
    method: 'GET',
    headers: {
      'Authorization': 'Bearer YOUR_AUTH_TOKEN',
      'Content-Type': 'application/json'
    }
  }
);

const data = await response.json();
```

```javascript
// Using axios
const response = await axios.get('/api/communication/getGroupMessages', {
  params: {
    class_id: 10,
    section_id: 'A'
  },
  headers: {
    'Authorization': 'Bearer YOUR_AUTH_TOKEN'
  }
});
```

### Example Response

```json
{
  "success": true,
  "data": [
    {
      "id": 1,
      "parentId": 5,
      "senderId": 123,
      "receiverId": 0,
      "message": "Hello everyone!",
      "isAttachment": 0,
      "created_at": "2026-02-09T05:50:00.000Z",
      "updated_at": "2026-02-09T05:50:00.000Z",
      "dateTime": "2026-02-09T05:50:00.000Z",
      "sender_name": "John Doe"
    },
    {
      "id": 2,
      "parentId": 5,
      "senderId": 456,
      "receiverId": 0,
      "message": "Hi John!",
      "isAttachment": 0,
      "created_at": "2026-02-09T05:51:00.000Z",
      "updated_at": "2026-02-09T05:51:00.000Z",
      "dateTime": "2026-02-09T05:51:00.000Z",
      "sender_name": "Jane Smith"
    }
  ]
}
```

### Response Fields

| Field | Type | Description |
|-------|------|-------------|
| `id` | Number | Message ID |
| `parentId` | Number | Communication thread ID |
| `senderId` | Number | ID of the message sender |
| `receiverId` | Number | Always 0 for group messages |
| `message` | String | The message content |
| `isAttachment` | Number | 0 for text, 1 for attachment |
| `created_at` | DateTime | Message creation timestamp |
| `updated_at` | DateTime | Message update timestamp |
| `dateTime` | DateTime | Message date/time |
| `sender_name` | String | Name of the sender (from employee_details or student_details) |

### Error Responses

#### Missing class_id
```json
{
  "error": "Missing required field: class_id or classId"
}
```
Status Code: `400 Bad Request`

#### No messages found
```json
{
  "success": true,
  "data": []
}
```
Status Code: `200 OK`

#### Server Error
```json
{
  "error": "Internal Server Error",
  "message": "Error details..."
}
```
Status Code: `500 Internal Server Error`

## How It Works

1. **Student enters group chat**: When a student navigates to a group chat screen, call this endpoint with the appropriate `class_id` and `section_id`.

2. **Backend processing**:
   - Constructs group identifier: `G_{class_id}_{section_id}`
   - Finds the communication thread for this group
   - Retrieves all messages from the `communication_message` table
   - Joins with `employee_details` and `student_details` to get sender names
   - Returns messages in chronological order (oldest first)

3. **Frontend display**: Use the returned data to populate the chat history in your UI.

## Integration Example

```javascript
// In your React Native component
useEffect(() => {
  const loadGroupMessages = async () => {
    try {
      const response = await axios.get('/api/communication/getGroupMessages', {
        params: {
          class_id: currentClass.id,
          section_id: currentSection.id
        }
      });
      
      if (response.data.success) {
        setMessages(response.data.data);
      }
    } catch (error) {
      console.error('Failed to load group messages:', error);
    }
  };

  loadGroupMessages();
}, [currentClass.id, currentSection.id]);
```

## Notes

- Messages are returned in ascending order by ID (oldest first)
- The endpoint automatically handles both `class_id`/`classId` and `section_id`/`sectionId` parameter naming conventions
- If no section is specified, it defaults to 'all'
- Empty array is returned if no messages exist for the group yet
- Sender names are automatically resolved from the database
