> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/No-Country-simulation/S02-26-Equipo-33-Web-App/llms.txt
> Use this file to discover all available pages before exploring further.

# Conversations

> Create and manage chat conversations between users

## Overview

Conversations represent chat threads between two users. Each conversation can optionally be linked to a horse listing (e.g., when a buyer contacts a seller about a specific horse).

## Authentication

All conversation endpoints require authentication via JWT token in the `Authorization` header.

```
Authorization: Bearer <your_jwt_token>
```

***

## Create or Get Conversation

<RequestExample>
  ```bash cURL theme={null}
  curl -X POST https://api.horsetrust.com/api/chat/conversations \
    -H "Authorization: Bearer <token>" \
    -H "Content-Type: application/json" \
    -d '{
      "recipient_id": "507f1f77bcf86cd799439011",
      "horse_id": "507f1f77bcf86cd799439012"
    }'
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch('https://api.horsetrust.com/api/chat/conversations', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      recipient_id: '507f1f77bcf86cd799439011',
      horse_id: '507f1f77bcf86cd799439012'
    })
  });

  const data = await response.json();
  ```

  ```python Python theme={null}
  import requests

  response = requests.post(
      'https://api.horsetrust.com/api/chat/conversations',
      headers={
          'Authorization': f'Bearer {token}',
          'Content-Type': 'application/json'
      },
      json={
          'recipient_id': '507f1f77bcf86cd799439011',
          'horse_id': '507f1f77bcf86cd799439012'
      }
  )

  data = response.json()
  ```
</RequestExample>

<ResponseExample>
  ```json Success Response theme={null}
  {
    "success": true,
    "data": {
      "_id": "65a1b2c3d4e5f6a7b8c9d0e1",
      "participants": [
        "507f1f77bcf86cd799439010",
        "507f1f77bcf86cd799439011"
      ],
      "horse_id": "507f1f77bcf86cd799439012",
      "last_message": {
        "text": "Is this horse still available?",
        "sender_id": "507f1f77bcf86cd799439010",
        "sent_at": "2024-03-15T10:30:00.000Z",
        "is_read": false
      },
      "created_at": "2024-03-15T10:30:00.000Z",
      "updated_at": "2024-03-15T10:30:00.000Z"
    }
  }
  ```

  ```json Error Response theme={null}
  {
    "success": false,
    "message": "Invalid recipient ID"
  }
  ```
</ResponseExample>

### POST `/api/chat/conversations`

Creates a new conversation or returns an existing one between the authenticated user and the recipient. If a conversation already exists between these two users (optionally for the same horse), the existing conversation is returned.

<ParamField body="recipient_id" type="string" required>
  MongoDB ObjectId of the user to start a conversation with. Must be a valid ObjectId and cannot be the current user's ID.
</ParamField>

<ParamField body="horse_id" type="string">
  MongoDB ObjectId of the horse listing this conversation is about. Optional. If provided, the conversation will be linked to this specific horse.
</ParamField>

### Response Fields

<ResponseField name="success" type="boolean" required>
  Indicates if the request was successful
</ResponseField>

<ResponseField name="data" type="object">
  The conversation object

  <ResponseField name="_id" type="string">
    Unique conversation identifier
  </ResponseField>

  <ResponseField name="participants" type="array">
    Array of exactly 2 user ObjectIds representing the participants in the conversation
  </ResponseField>

  <ResponseField name="horse_id" type="string">
    MongoDB ObjectId of the related horse listing (if applicable)
  </ResponseField>

  <ResponseField name="last_message" type="object">
    Snapshot of the most recent message in the conversation

    <ResponseField name="text" type="string">
      Message content
    </ResponseField>

    <ResponseField name="sender_id" type="string">
      ObjectId of the user who sent the message
    </ResponseField>

    <ResponseField name="sent_at" type="string">
      ISO 8601 timestamp when the message was sent
    </ResponseField>

    <ResponseField name="is_read" type="boolean">
      Whether the message has been read by the recipient
    </ResponseField>
  </ResponseField>

  <ResponseField name="created_at" type="string">
    ISO 8601 timestamp when the conversation was created
  </ResponseField>

  <ResponseField name="updated_at" type="string">
    ISO 8601 timestamp when the conversation was last updated
  </ResponseField>
</ResponseField>

<ResponseField name="message" type="string">
  Error message (only present when success is false)
</ResponseField>

### Error Responses

* **400 Bad Request**: Invalid recipient ID or attempting to message yourself
* **500 Internal Server Error**: Server error occurred

***

## List Conversations

<RequestExample>
  ```bash cURL theme={null}
  curl https://api.horsetrust.com/api/chat/conversations \
    -H "Authorization: Bearer <token>"
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch('https://api.horsetrust.com/api/chat/conversations', {
    headers: {
      'Authorization': `Bearer ${token}`
    }
  });

  const data = await response.json();
  ```

  ```python Python theme={null}
  import requests

  response = requests.get(
      'https://api.horsetrust.com/api/chat/conversations',
      headers={'Authorization': f'Bearer {token}'}
  )

  data = response.json()
  ```
</RequestExample>

<ResponseExample>
  ```json Success Response theme={null}
  {
    "success": true,
    "data": [
      {
        "_id": "65a1b2c3d4e5f6a7b8c9d0e1",
        "participants": [
          {
            "_id": "507f1f77bcf86cd799439010",
            "full_name": "John Smith",
            "profile_picture_url": "https://cdn.horsetrust.com/users/john.jpg",
            "seller_profile": {
              "is_verified_badge": true
            }
          },
          {
            "_id": "507f1f77bcf86cd799439011",
            "full_name": "Jane Doe",
            "profile_picture_url": "https://cdn.horsetrust.com/users/jane.jpg",
            "seller_profile": {
              "is_verified_badge": false
            }
          }
        ],
        "horse_id": {
          "_id": "507f1f77bcf86cd799439012",
          "name": "Thunder",
          "photos": [
            {
              "url": "https://cdn.horsetrust.com/horses/thunder-1.jpg",
              "is_primary": true
            }
          ]
        },
        "last_message": {
          "text": "Yes, Thunder is still available!",
          "sender_id": "507f1f77bcf86cd799439011",
          "sent_at": "2024-03-15T10:35:00.000Z",
          "is_read": false
        },
        "created_at": "2024-03-15T10:30:00.000Z",
        "updated_at": "2024-03-15T10:35:00.000Z"
      }
    ]
  }
  ```
</ResponseExample>

### GET `/api/chat/conversations`

Returns all conversations for the authenticated user, sorted by most recently updated first. Results include populated participant details and horse information.

### Response Fields

<ResponseField name="success" type="boolean" required>
  Indicates if the request was successful
</ResponseField>

<ResponseField name="data" type="array">
  Array of conversation objects sorted by `updated_at` (most recent first)

  <ResponseField name="_id" type="string">
    Unique conversation identifier
  </ResponseField>

  <ResponseField name="participants" type="array">
    Array of populated user objects

    <ResponseField name="_id" type="string">
      User's unique identifier
    </ResponseField>

    <ResponseField name="full_name" type="string">
      User's full name
    </ResponseField>

    <ResponseField name="profile_picture_url" type="string">
      URL to the user's profile picture
    </ResponseField>

    <ResponseField name="seller_profile" type="object">
      Seller profile information

      <ResponseField name="is_verified_badge" type="boolean">
        Whether the seller has a verified badge
      </ResponseField>
    </ResponseField>
  </ResponseField>

  <ResponseField name="horse_id" type="object">
    Populated horse object (if conversation is linked to a horse)

    <ResponseField name="_id" type="string">
      Horse's unique identifier
    </ResponseField>

    <ResponseField name="name" type="string">
      Horse's name
    </ResponseField>

    <ResponseField name="photos" type="array">
      Array of horse photos
    </ResponseField>
  </ResponseField>

  <ResponseField name="last_message" type="object">
    Most recent message in the conversation (see Create or Get Conversation for fields)
  </ResponseField>

  <ResponseField name="created_at" type="string">
    ISO 8601 timestamp when the conversation was created
  </ResponseField>

  <ResponseField name="updated_at" type="string">
    ISO 8601 timestamp when the conversation was last updated
  </ResponseField>
</ResponseField>

### Error Responses

* **500 Internal Server Error**: Server error occurred

***

## Socket.io Events

### Join Conversation Room

Join a specific conversation room to receive real-time messages.

```javascript theme={null}
socket.emit('join_conversation', conversationId);
```

<ParamField body="conversationId" type="string" required>
  The ID of the conversation to join
</ParamField>

### New Message Event

Receive new messages in conversations you've joined.

```javascript theme={null}
socket.on('new_message', (message) => {
  console.log('New message:', message);
});
```

**Event Payload:**

```json theme={null}
{
  "_id": "65a1b2c3d4e5f6a7b8c9d0e3",
  "conversation_id": "65a1b2c3d4e5f6a7b8c9d0e1",
  "sender_id": {
    "_id": "507f1f77bcf86cd799439010",
    "full_name": "John Smith",
    "profile_picture_url": "https://cdn.horsetrust.com/users/john.jpg"
  },
  "text": "Is this horse still available?",
  "is_read": false,
  "sent_at": "2024-03-15T10:30:00.000Z"
}
```

### Message Notification Event

Receive notifications when someone sends you a message (delivered to your personal user room).

```javascript theme={null}
socket.on('message_notification', (notification) => {
  console.log('New message notification:', notification);
});
```

**Event Payload:**

```json theme={null}
{
  "conversation_id": "65a1b2c3d4e5f6a7b8c9d0e1",
  "sender": "507f1f77bcf86cd799439010",
  "preview": "Is this horse still available?"
}
```

<Note>
  The preview field contains the first 60 characters of the message text.
</Note>

***

## Data Model

### Conversation Schema

```javascript theme={null}
{
  participants: [ObjectId, ObjectId],  // Exactly 2 users (required)
  horse_id: ObjectId,                   // Optional reference to Horse
  last_message: {
    text: String,
    sender_id: ObjectId,
    sent_at: Date,
    is_read: Boolean
  },
  created_at: Date,
  updated_at: Date
}
```

### Validation Rules

* Conversations must have exactly 2 participants
* Participants must be valid user ObjectIds
* Users cannot create conversations with themselves
* The `last_message` field is automatically updated when new messages are sent

### Indexes

* `participants`: Used for efficiently finding all conversations for a user
