# Event Chat System Documentation

## Overview

The Event Chat System allows users to create and participate in group chats for events. Users can join event chats, send messages, share attachments, and receive real-time updates through WebSocket connections.

## Database Models

### EventChat Model
- **Location**: `src/db/models/eventChatModel.js`
- **Purpose**: Represents a group chat for an event
- **Key Fields**:
  - `eventId`: Reference to the event
  - `chatName`: Display name of the chat
  - `members`: Array of chat participants with roles
  - `totalMembers`: Count of active members
  - `totalMessages`: Count of messages in chat
  - `lastMessage`: Last message info for chat preview
  - `createdBy`: Event creator (becomes admin)

### EventChatMessage Model
- **Location**: `src/db/models/eventChatMessageModel.js`
- **Purpose**: Represents individual chat messages
- **Key Fields**:
  - `chatId`: Reference to the event chat
  - `eventId`: Direct reference to event
  - `content`: Message text content
  - `messageType`: 'text', 'image', 'file', or 'system'
  - `sender`: User who sent the message
  - `attachment`: File/media information for attachments
  - `isDeleted`: Soft delete flag

## REST API Endpoints

### Base URL: `/api/v1/events`

All endpoints require authentication (`Authorization: Bearer <token>`)

#### 1. Join Event Chat
- **Endpoint**: `POST /:eventId/chat/join`
- **Purpose**: Join an event's group chat (creates chat if doesn't exist)
- **Parameters**: 
  - `eventId` (URL parameter)
- **Response**:
```json
{
  "success": true,
  "message": "Successfully joined event chat",
  "data": {
    "chat": {
      "eventId": "event_id",
      "chatName": "Event Name - Event Chat",
      "members": [...],
      "totalMembers": 5
    },
    "recentMessages": [...]
  }
}
```

#### 2. Leave Event Chat
- **Endpoint**: `POST /:eventId/chat/leave`
- **Purpose**: Leave an event's group chat
- **Parameters**: 
  - `eventId` (URL parameter)
- **Response**:
```json
{
  "success": true,
  "message": "Successfully left event chat"
}
```

#### 3. Get Chat Messages (Paginated)
- **Endpoint**: `GET /:eventId/chat/messages`
- **Purpose**: Retrieve chat messages with pagination
- **Parameters**: 
  - `eventId` (URL parameter)
  - `page` (query, default: 1)
  - `limit` (query, default: 50)
  - `before` (query, optional timestamp)
- **Response**:
```json
{
  "success": true,
  "message": "Messages retrieved successfully",
  "data": {
    "messages": [...],
    "pagination": {
      "currentPage": 1,
      "totalPages": 5,
      "totalMessages": 250,
      "hasMore": true
    }
  }
}
```

#### 4. Send Attachment Message
- **Endpoint**: `POST /:eventId/chat/attachment`
- **Purpose**: Send file/image attachment to chat
- **Content-Type**: `multipart/form-data`
- **Parameters**: 
  - `eventId` (URL parameter)
  - `attachment` (file, max 10MB)
  - `content` (optional text description)
- **Allowed File Types**: Images (JPEG, PNG, GIF, WebP), PDF, Word documents, Text files
- **Response**:
```json
{
  "success": true,
  "message": "Attachment sent successfully",
  "data": {
    "message": {
      "content": "Optional description",
      "messageType": "image",
      "attachment": {
        "fileName": "image.jpg",
        "fileUrl": "/uploads/chat-attachments/...",
        "fileSize": 1024000,
        "mimeType": "image/jpeg"
      },
      "sender": {...}
    }
  }
}
```

#### 5. Get Chat Details
- **Endpoint**: `GET /:eventId/chat`
- **Purpose**: Get event chat information and members
- **Parameters**: 
  - `eventId` (URL parameter)
- **Response**:
```json
{
  "success": true,
  "message": "Chat details retrieved successfully",
  "data": {
    "chat": {
      "eventId": "event_id",
      "chatName": "Event Name - Event Chat",
      "members": [
        {
          "userId": "user_id",
          "role": "admin",
          "joinedAt": "2024-01-01T00:00:00.000Z",
          "user": {
            "email": "user@example.com",
            "userProfile": {...}
          }
        }
      ],
      "totalMembers": 5,
      "totalMessages": 123
    }
  }
}
```

#### 6. Get User's Event Chats
- **Endpoint**: `GET /chats`
- **Purpose**: Get all event chats the user is a member of
- **Response**:
```json
{
  "success": true,
  "message": "User chats retrieved successfully",
  "data": {
    "chats": [
      {
        "eventId": "event_id",
        "chatName": "Event Name - Event Chat",
        "event": {
          "name": "Event Name",
          "eventDate": "2024-01-01",
          "eventImages": [...]
        },
        "lastMessage": {
          "content": "Last message content",
          "sender": {...},
          "sentAt": "2024-01-01T00:00:00.000Z"
        },
        "totalMembers": 5,
        "totalMessages": 123
      }
    ]
  }
}
```

## WebSocket Events

### Connection
- **URL**: WebSocket connection to server
- **Authentication**: Include JWT token in handshake
- **Auto-Chat Creation**: Event chats are automatically created when users join if they don't exist
```javascript
const socket = io('ws://localhost:3050', {
  auth: {
    token: 'your-jwt-token'
  }
});
```

### Client Events (Emit)

#### 1. joinedEventChat
- **Purpose**: Join an event chat room and get recent messages (creates chat if it doesn't exist)
- **Payload**:
```javascript
socket.emit('joinedEventChat', { 
  eventId: 'event_id' // This is the Event ID, not EventChat ID
}, (response) => {
  if (response.success) {
    const { chat, members, recentMessages } = response.data;
    // Handle successful join - chat will be created if it didn't exist
  }
});
```
- **Response**:
```javascript
{
  success: true,
  data: {
    chat: { /* EventChat object */ },
    members: [
      {
        userId: "user_id",
        role: "admin",
        joinedAt: "2024-01-01T00:00:00.000Z",
        user: {
          email: "user@example.com",
          userProfile: { /* Profile data */ }
        }
      }
    ],
    recentMessages: [ /* Last 50 messages */ ]
  }
}
```

#### 2. leaveEventChat
- **Purpose**: Leave an event chat room
- **Payload**:
```javascript
socket.emit('leaveEventChat', { 
  eventId: 'event_id' 
}, (response) => {
  console.log(response.message);
});
```

#### 3. sendEventChatMessage
- **Purpose**: Send a text message to event chat
- **Payload**:
```javascript
socket.emit('sendEventChatMessage', {
  eventId: 'event_id',
  content: 'Hello everyone!',
  messageType: 'text'
}, (response) => {
  if (response.success) {
    console.log('Message sent:', response.data);
  }
});
```

#### 4. typing
- **Purpose**: Send typing indicator
- **Payload**:
```javascript
socket.emit('typing', {
  eventId: 'event_id',
  isTyping: true
});
```

### Server Events (Listen)

#### 1. NewlyJoinedUser
- **Purpose**: Notifies when a new user joins the chat
- **Payload**:
```javascript
{
  userId: "user_id",
  user: { /* User profile data */ },
  joinedAt: "2024-01-01T00:00:00.000Z"
}
```
- **Usage**:
```javascript
socket.on('NewlyJoinedUser', (data) => {
  // Update members list
  // Show "User joined" notification
});
```

#### 2. NewMessage
- **Purpose**: Receive new messages in real-time
- **Payload**:
```javascript
{
  message: {
    _id: "message_id",
    content: "Hello everyone!",
    messageType: "text",
    sender: {
      _id: "user_id",
      email: "user@example.com",
      userProfile: { /* Profile data */ }
    },
    createdAt: "2024-01-01T00:00:00.000Z"
  },
  chatId: "chat_id",
  eventId: "event_id"
}
```
- **Usage**:
```javascript
socket.on('NewMessage', (data) => {
  // Add message to chat interface
  // Play notification sound
  // Update last message in chat list
});
```

#### 3. UserLeft
- **Purpose**: Notifies when a user leaves the chat
- **Payload**:
```javascript
{
  userId: "user_id",
  user: { /* User profile data */ },
  leftAt: "2024-01-01T00:00:00.000Z"
}
```
- **Usage**:
```javascript
socket.on('UserLeft', (data) => {
  // Update members list
  // Show "User left" notification
});
```

#### 4. userTyping
- **Purpose**: Shows typing indicators from other users
- **Payload**:
```javascript
{
  userId: "user_id",
  user: { /* User profile data */ },
  isTyping: true,
  eventId: "event_id"
}
```
- **Usage**:
```javascript
socket.on('userTyping', (data) => {
  if (data.isTyping) {
    // Show "User is typing..." indicator
  } else {
    // Hide typing indicator
  }
});
```

## Implementation Example

### Frontend Chat Integration
```javascript
class EventChatManager {
  constructor(eventId, token) {
    this.eventId = eventId;
    this.socket = io('ws://localhost:3050', {
      auth: { token }
    });
    this.setupEventListeners();
  }

  setupEventListeners() {
    // Listen for new messages
    this.socket.on('NewMessage', (data) => {
      this.displayMessage(data.message);
    });

    // Listen for users joining
    this.socket.on('NewlyJoinedUser', (data) => {
      this.showNotification(`${data.user.email} joined the chat`);
      this.updateMembersList();
    });

    // Listen for users leaving
    this.socket.on('UserLeft', (data) => {
      this.showNotification(`${data.user.email} left the chat`);
      this.updateMembersList();
    });

    // Listen for typing indicators
    this.socket.on('userTyping', (data) => {
      this.showTypingIndicator(data.user, data.isTyping);
    });
  }

  joinChat() {
    this.socket.emit('joinedEventChat', { 
      eventId: this.eventId 
    }, (response) => {
      if (response.success) {
        this.displayMessages(response.data.recentMessages);
        this.displayMembers(response.data.members);
      }
    });
  }

  sendMessage(content) {
    this.socket.emit('sendEventChatMessage', {
      eventId: this.eventId,
      content: content,
      messageType: 'text'
    }, (response) => {
      if (!response.success) {
        console.error('Failed to send message:', response.message);
      }
    });
  }

  leaveChat() {
    this.socket.emit('leaveEventChat', { 
      eventId: this.eventId 
    });
  }
}
```

## Error Handling

### Common Error Responses
- **401 Unauthorized**: Invalid or missing authentication token
- **403 Forbidden**: User is not a member of the chat
- **404 Not Found**: Event or chat not found
- **400 Bad Request**: Invalid request data
- **500 Internal Server Error**: Server-side error

### Socket Error Handling
```javascript
socket.on('connect_error', (error) => {
  console.error('Connection failed:', error.message);
  // Handle authentication errors
  if (error.message === 'Authentication failed') {
    // Redirect to login
  }
});
```

## Security Features

1. **Authentication**: All routes and socket connections require valid JWT tokens
2. **Authorization**: Users must be chat members to access messages
3. **File Upload Security**: 
   - File type validation
   - Size limits (10MB)
   - Secure file storage
4. **Rate Limiting**: Socket events include built-in rate limiting
5. **Data Validation**: All inputs are validated using Joi schemas

## Performance Considerations

1. **Message Pagination**: Large chat histories are paginated (50 messages per page)
2. **Recent Messages**: Only last 50 messages loaded on chat join
3. **Database Indexes**: Optimized queries with proper indexing
4. **File Storage**: Attachments stored on disk/S3, not in database
5. **Socket Rooms**: Efficient event-based room management

## CURL Examples

### 1. Join Event Chat
```bash
curl -X POST "http://localhost:3050/api/v1/events/{eventId}/chat/join" \
  -H "Content-Type: application/json" \
  -H "authtoken: Bearer your-jwt-token"
```

### 2. Leave Event Chat
```bash
curl -X POST "http://localhost:3050/api/v1/events/{eventId}/chat/leave" \
  -H "Content-Type: application/json" \
  -H "authtoken: Bearer your-jwt-token"
```

### 3. Get Chat Messages (Paginated)
```bash
curl -X GET "http://localhost:3050/api/v1/events/{eventId}/chat/messages?page=1&limit=50" \
  -H "Content-Type: application/json" \
  -H "authtoken: Bearer your-jwt-token"
```

### 4. Send Attachment Message
```bash
curl -X POST "http://localhost:3050/api/v1/events/{eventId}/chat/attachment" \
  -H "authtoken: Bearer your-jwt-token" \
  -F "attachment=@/path/to/your/file.jpg" \
  -F "content=Check out this image!"
```

### 5. Get Chat Details
```bash
curl -X GET "http://localhost:3050/api/v1/events/{eventId}/chat" \
  -H "Content-Type: application/json" \
  -H "authtoken: Bearer your-jwt-token"
```

### 6. Get User's Event Chats
```bash
curl -X GET "http://localhost:3050/api/v1/events/chats" \
  -H "Content-Type: application/json" \
  -H "authtoken: Bearer your-jwt-token"
```

### Example with Variables
```bash
# Set variables
EVENT_ID="your-event-id-here"
JWT_TOKEN="your-jwt-token-here"
BASE_URL="http://localhost:3050"

# Join event chat
curl -X POST "$BASE_URL/api/v1/events/$EVENT_ID/chat/join" \
  -H "Content-Type: application/json" \
  -H "authtoken: Bearer $JWT_TOKEN"

# Get messages with pagination
curl -X GET "$BASE_URL/api/v1/events/$EVENT_ID/chat/messages?page=1&limit=20&before=2024-01-01T00:00:00.000Z" \
  -H "Content-Type: application/json" \
  -H "authtoken: Bearer $JWT_TOKEN"

# Upload image attachment
curl -X POST "$BASE_URL/api/v1/events/$EVENT_ID/chat/attachment" \
  -H "authtoken: Bearer $JWT_TOKEN" \
  -F "attachment=@photo.jpg" \
  -F "content=Here's a photo from the event!"
```

## Testing with Postman

### Environment Variables
Create these variables in Postman:
- `baseUrl`: `http://localhost:3050`
- `authToken`: Your JWT token
- `eventId`: Event ID for testing

### Headers for All Requests
- `Content-Type`: `application/json`
- `authtoken`: `Bearer {{authToken}}`

### File Upload Request (Attachment)
1. Set method to POST
2. URL: `{{baseUrl}}/api/v1/events/{{eventId}}/chat/attachment`
3. Headers: `authtoken: Bearer {{authToken}}`
4. Body: form-data
   - Key: `attachment` (File)
   - Key: `content` (Text) - Optional description

## Future Enhancements

1. **Message Reactions**: Like/react to messages
2. **Message Threading**: Reply to specific messages
3. **Voice Messages**: Audio message support
4. **Message Search**: Full-text search within chats
5. **Push Notifications**: Mobile push notifications for new messages
6. **Read Receipts**: Track who has read messages
7. **Chat Moderation**: Admin controls for message deletion/user management