# Support Chat System

This support chat system provides real-time chat functionality between users and support agents based on help desk tickets.

## Features

- 💬 Real-time chat messaging
- 🎫 Support chats linked to help desk tickets
- 👥 Support agent assignment
- 📱 Online status tracking
- 📎 File attachments support
- ✅ Message read status
- ✏️ Message editing
- 💬 Reply to messages
- 📊 Unread message count

## Database Schema

### Support Chat Schema

```typescript
{
  help_desk_id: ObjectId,           // Reference to HelpDesk
  user_id: ObjectId,                // User who created the ticket
  assigned_support_agent: ObjectId, // Assigned support agent
  status: "active" | "closed" | "resolved",
  last_message_at: Date,
  is_user_online: Boolean,
  is_support_online: Boolean,
  timestamps: true
}
```

### Support Message Schema

```typescript
{
  support_chat_id: ObjectId,        // Reference to SupportChat
  sender_id: ObjectId,              // Message sender
  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
}
```

## API Endpoints

### Support Chat Management

#### Create Support Chat

```
POST /api/support/create
Body: {
  "helpDeskId": "string",
  "userId": "string",
  "assignedSupportAgent": "string" // optional
}
```

#### Get Support Chat by Help Desk ID

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

#### Get User's Support Chats

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

#### Assign Support Agent

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

#### Close Support Chat

```
PUT /api/support/close/:supportChatId
```

### Message Management

#### Send Message

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

#### Get Messages

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

#### Mark Messages as Read

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

#### Edit Message

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

### Status Management

#### Update User Online Status

```
PUT /api/support/status/user-online
Body: {
  "supportChatId": "string",
  "isOnline": boolean
}
```

#### Update Support Agent Online Status

```
PUT /api/support/status/support-online
Body: {
  "supportChatId": "string",
  "isOnline": boolean
}
```

#### Get Unread Message Count

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

## Usage Examples

### Frontend Integration

#### Initialize Chat for Help Desk Ticket

```javascript
// When viewing a help desk ticket, get or create support chat
const response = await fetch(`/api/support/helpdesk/${helpDeskId}`);
const supportChat = await response.json();

if (!supportChat.success) {
  // Create new support chat
  const createResponse = await fetch("/api/support/create", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      helpDeskId: helpDeskId,
      userId: currentUserId,
    }),
  });
}
```

#### Send Message

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

#### Load Chat Messages

```javascript
const loadMessages = async (chatId, page = 1) => {
  const response = await fetch(
    `/api/support/messages/${chatId}?page=${page}&limit=50`
  );
  const data = await response.json();
  return data;
};
```

#### Real-time Updates (WebSocket recommended)

```javascript
// Mark user as online when entering chat
await fetch("/api/support/status/user-online", {
  method: "PUT",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    supportChatId: chatId,
    isOnline: true,
  }),
});

// Mark messages as read when viewing
await fetch("/api/support/messages/mark-read", {
  method: "PUT",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    supportChatId: chatId,
    userId: currentUserId,
  }),
});
```

## Integration with Help Desk

The support chat system is automatically integrated with the help desk system:

1. **Auto-Creation**: When a new help desk ticket is created, a support chat is automatically created
2. **Linked Data**: Support chats are linked to help desk tickets via `help_desk_id`
3. **User Association**: The same user who created the help desk ticket owns the support chat

## Features for Different User Types

### For Regular Users

- View support chats for their help desk tickets
- Send messages to support agents
- Receive real-time responses
- Upload attachments
- Edit their own messages
- See online status of support agents

### For Support Agents

- View all support chats assigned to them
- Respond to user messages
- Transfer chats to other agents
- Close resolved chats
- See user online status
- Access help desk ticket details

### For Administrators

- View all support chats
- Assign support agents to chats
- Monitor chat activity
- Generate reports on support performance

## 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. **Chat Templates**: Add quick response templates for support agents
5. **Chat Analytics**: Add metrics and reporting features
6. **Typing Indicators**: Show when someone is typing
7. **Message Reactions**: Add emoji reactions to messages
8. **Chat Transcripts**: Export chat history as PDF/email

## Error Handling

All endpoints return consistent error responses:

```json
{
  "success": false,
  "message": "Error description"
}
```

## Security Considerations

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