# Support Chat System

This support chat system provides messaging functionality for help desk tickets, allowing direct communication between users and support agents.

## Features

- 💬 Direct messaging on help desk tickets
- 👥 Support agent assignment via existing help desk system
- 📎 File attachments support
- ✅ Message read status
- ✏️ Message editing
- 💬 Reply to messages
- 📊 Unread message count

## Database Schema

### Support Message Schema (Only Schema Needed)

```typescript
{
  help_desk_id: ObjectId,           // Reference to HelpDesk ticket
  sender_id: ObjectId,              // Message sender (user or support agent)
  message_type: "user" | "support" | "system",
  message_content: String,
  attachment_url: String,           // Optional file attachment
  attachment_type: "image" | "document" | "video" | "audio",
  message_status: "sent" | "delivered" | "read",
  is_edited: Boolean,
  edited_at: Date,
  reply_to_message_id: ObjectId,    // Optional reply reference
  timestamps: true
}
```

**Note**: This system uses the existing `HelpDesk` schema instead of creating a separate support chat schema. All chat functionality is built around help desk tickets.

## API Endpoints

### Help Desk Management

#### Get Help Desk by ID

```
GET /api/support/helpdesk/:helpDeskId
```

#### Get User's Help Desk Tickets

```
GET /api/support/user/:userId?page=1&limit=10
```

#### Assign Support Agent

```
PUT /api/support/assign-agent
Body: {
  "helpDeskId": "string",
  "supportAgentId": "string"
}
```

#### Close Help Desk Ticket

```
PUT /api/support/close/:helpDeskId
```

### Message Management

#### Send Message

```
POST /api/support/message/send
Body: {
  "helpDeskId": "string",
  "senderId": "string",
  "messageContent": "string",
  "messageType": "user" | "support" | "system",
  "attachmentUrl": "string",      // optional
  "attachmentType": "string",     // optional
  "replyToMessageId": "string"    // optional
}
```

#### Get Messages for Help Desk Ticket

```
GET /api/support/messages/:helpDeskId?page=1&limit=50
```

#### Mark Messages as Read

```
PUT /api/support/messages/mark-read
Body: {
  "helpDeskId": "string",
  "userId": "string"
}
```

#### Edit Message

```
PUT /api/support/message/edit
Body: {
  "messageId": "string",
  "newContent": "string",
  "userId": "string"
}
```

### Utility Endpoints

#### Get Unread Message Count

```
GET /api/support/unread-count/:userId
```

#### Get Help Desk Tickets with Message Activity

```
GET /api/support/helpdesks-with-messages?supportAgentId=string&page=1&limit=10
```

## Usage Examples

### Frontend Integration

#### Load Messages for Help Desk Ticket

```javascript
// Get messages for a help desk ticket
const response = await fetch(
  `/api/support/messages/${helpDeskId}?page=1&limit=50`
);
const data = await response.json();

if (data.success) {
  const messages = data.data;
  const pagination = data.pagination;
}
```

#### Send Message

```javascript
const sendMessage = async (helpDeskId, message) => {
  const response = await fetch("/api/support/message/send", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      helpDeskId: helpDeskId,
      senderId: currentUserId,
      messageContent: message,
      messageType: "user",
    }),
  });
  return response.json();
};
```

#### Load Help Desk Tickets with Chat Activity

```javascript
const loadHelpDesksWithMessages = async (supportAgentId, page = 1) => {
  const url = `/api/support/helpdesks-with-messages?supportAgentId=${supportAgentId}&page=${page}&limit=10`;
  const response = await fetch(url);
  const data = await response.json();
  return data;
};
```

#### Mark Messages as Read

```javascript
const markAsRead = async (helpDeskId, userId) => {
  await fetch("/api/support/messages/mark-read", {
    method: "PUT",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      helpDeskId: helpDeskId,
      userId: userId,
    }),
  });
};
```

## Integration with Help Desk

The support chat system is fully integrated with the existing help desk system:

1. **Direct Integration**: Messages are directly linked to help desk tickets via `help_desk_id`
2. **Simplified Structure**: No separate chat entity - everything is based on existing help desk tickets
3. **Agent Assignment**: Uses the existing `assigned_to` field in help desk schema
4. **Status Management**: Uses existing help desk status for ticket management

## Features for Different User Types

### For Regular Users

- Send messages on their help desk tickets
- View message history for their tickets
- Upload attachments
- Edit their own messages
- See read status of messages

### For Support Agents

- View all help desk tickets assigned to them
- Respond to user messages
- Access help desk ticket details
- See message activity across tickets

### For Administrators

- View all help desk tickets with message activity
- Assign support agents to tickets
- Monitor chat activity

## Simplified Workflow

1. **Ticket Creation**: User creates help desk ticket (existing functionality)
2. **Messaging**: User or support agent can send messages on the ticket
3. **Assignment**: Admin assigns support agent to ticket (existing functionality)
4. **Resolution**: Support agent helps resolve the issue through messages
5. **Closure**: Ticket is closed using existing help desk status

## Next Steps for Enhancement

1. **WebSocket Integration**: Add real-time messaging with Socket.io
2. **File Upload**: Implement file upload endpoint for attachments
3. **Push Notifications**: Add notifications for new messages
4. **Message Templates**: Add quick response templates for support agents
5. **Typing Indicators**: Show when someone is typing
6. **Message Reactions**: Add emoji reactions to messages

## Security Considerations

- All endpoints should be protected with authentication middleware
- Users can only access their own help desk tickets and messages
- Support agents can only access assigned tickets
- Message editing is only allowed by the original sender
- File uploads should be validated and scanned
