> **Client contract note:** Apply [`shared/response-envelope.md`](../shared/response-envelope.md) to JSON responses after the response-contract release. Legacy wrapper examples below may reflect the prior API; the documented endpoint-specific payload fields are still useful. Not staging-verified.

# Chat API — Flutter

Source: [`modules/Chat/Routes/api.php`](https://gitlab.com/alalmiyalhura/outlet/-/blob/main/modules/Chat/Routes/api.php).

> **Verification:** HTTP methods, paths, route-level authentication and route comments are confirmed from source. The detailed contracts in the verified section below are sourced from the controller and presenter; the earlier route inventory is superseded by that section. Do not treat illustrative placeholders as real API payloads.

Endpoints in this file: **6**.

## `GET /api/conversations`

- **Authentication:** Bearer token (`auth:sanctum`)
- **Permission:** User ownership enforced by application
- **Path parameters:** None
- **Query parameters:** Not verified from controller / request yet.
- **Request body:** No body expected for GET.
- **Success response:** Not verified from presenter / resource yet.
- **Error responses:** Authentication/authorization/validation and business errors depend on middleware and handler; status and JSON shape pending verification.

## `GET /api/conversations/unread`

- **Authentication:** Bearer token (`auth:sanctum`)
- **Permission:** User ownership enforced by application
- **Path parameters:** None
- **Query parameters:** Not verified from controller / request yet.
- **Request body:** No body expected for GET.
- **Success response:** Not verified from presenter / resource yet.
- **Error responses:** Authentication/authorization/validation and business errors depend on middleware and handler; status and JSON shape pending verification.

## `GET /api/conversations/{conversation}`

- **Authentication:** Bearer token (`auth:sanctum`)
- **Permission:** User ownership enforced by application
- **Path parameters:** conversation
- **Query parameters:** Not verified from controller / request yet.
- **Request body:** No body expected for GET.
- **Success response:** Not verified from presenter / resource yet.
- **Error responses:** Authentication/authorization/validation and business errors depend on middleware and handler; status and JSON shape pending verification.

## `GET /api/conversations/{conversation}/messages`

- **Authentication:** Bearer token (`auth:sanctum`)
- **Permission:** User ownership enforced by application
- **Path parameters:** conversation
- **Query parameters:** Not verified from controller / request yet.
- **Request body:** No body expected for GET.
- **Success response:** Not verified from presenter / resource yet.
- **Error responses:** Authentication/authorization/validation and business errors depend on middleware and handler; status and JSON shape pending verification.

## `POST /api/conversations/{conversation}/messages`

- **Authentication:** Bearer token (`auth:sanctum`)
- **Permission:** User ownership enforced by application
- **Path parameters:** conversation
- **Query parameters:** Not verified from controller / request yet.
- **Request body:** Requires controller / FormRequest verification; do not assume an empty body.
- **Success response:** Not verified from presenter / resource yet.
- **Error responses:** Authentication/authorization/validation and business errors depend on middleware and handler; status and JSON shape pending verification.

## `POST /api/conversations/{conversation}/read`

- **Authentication:** Bearer token (`auth:sanctum`)
- **Permission:** User ownership enforced by application
- **Path parameters:** conversation
- **Query parameters:** Not verified from controller / request yet.
- **Request body:** Requires controller / FormRequest verification; do not assume an empty body.
- **Success response:** Not verified from presenter / resource yet.
- **Error responses:** Authentication/authorization/validation and business errors depend on middleware and handler; status and JSON shape pending verification.


---
## Verified Flutter contracts — source audit (2026-11-22)

**Canonical API prefix:** `/api/v1` as documented in controller/presenter endpoint strings. Earlier `/api/conversations` route inventory above is relative to the API route registration; use the deployed route list to confirm gateway/base URL. All six endpoints require `Authorization: Bearer <token>` (`auth:sanctum`). A conversation is accessible only to its buyer or seller; unrelated users receive 404. `{conversation}` accepts numeric conversation ID (1–18 digits) **or** order reference matching `[A-Za-z]{3}-[0-9]{4,12}`. Source: [routes](https://gitlab.com/alalmiyalhura/outlet/-/blob/main/modules/Chat/Routes/api.php), [controller](https://gitlab.com/alalmiyalhura/outlet/-/blob/main/modules/Chat/Interfaces/Http/Controllers/ConversationController.php), [presenter](https://gitlab.com/alalmiyalhura/outlet/-/blob/main/modules/Chat/Interfaces/Http/Presenters/ChatViews.php).

### GET `/api/v1/conversations` — inbox
| Query | Type | Validation / default |
|---|---|---|
| `role` | string? | `all`, `buy`, `sell`; default `all` |
| `per_page` | integer? | 1..`chat.page_size_max` (configured, fallback 100); default 20 |

Response **200** is a top-level pagination object, **not** `{data:{...}}`:
| Field | Type | Meaning |
|---|---|---|
| `data` | array of conversation rows | Current page |
| `links` | object | `first`, `last`, `prev`, `next` URL or null |
| `meta` | object | `current_page`, `from`, `last_page`, `per_page`, `to`, `total`, `title`, `filters[]`, `unread_total`, `empty`, `footer` |
| `meta.filters[]` | object | `key`, `label`, `active` |
| `meta.empty` | object/null | `title`, `body` only when no conversations |

**`data[]` row schema:**
| Field | Type | Meaning |
|---|---|---|
| `id` | integer | Conversation ID |
| `order_ref` | string | Related order reference |
| `role` / `role_label` | string / string | `buy` or `sell`, localized label |
| `other_party` | object | `name`, `initial`, `role` (`buyer`/`seller`), `role_label` |
| `item` | object | `title`, `count`, `image_url` (string/null), `alt` |
| `last_message` | object | `preview`, `is_image`, `from_me`, `hidden`, `sent_at` (ISO/null) |
| `time_label` / `last_activity_at` | string / ISO string | Display time and timestamp |
| `unread_count` / `has_unread` | integer / boolean | Unread state |
| `status` / `read_only` / `read_only_label` | string / boolean / string? | Closed conversations cannot send |
| `endpoints` | object | `messages`, `send`, `read` paths |

### GET `/api/v1/conversations/unread` — tab badge
**200**: `data.total` (integer), `data.has_unread` (boolean), `data.label` (localized string), plus other unread counters returned by `ChatQueries::unread()` (their exact keys require inspecting that query). No query or body.

### GET `/api/v1/conversations/{conversation}` — thread header
**200**: `{ "data": <header> }`.

| Header field | Type / shape |
|---|---|
| `id`, `order_ref`, `role`, `status`, `read_only`, `close_reason` | integer, string, string, string, boolean, string/null |
| `other_party` | `{name,initial,role,role_label}` |
| `subtitle`, `closed_banner`, `safety_notice` | string, string/null, string |
| `order` | `{ref,item_title,items_count,image_url,alt,status,status_key,status_label,tone,screen,endpoint}`; order status fields may be null |
| `composer` | `{enabled,placeholder,max_length,images_max,attach_enabled,attach_label,send_label,upload_endpoint,send_endpoint}` |
| `unread_count`, `last_seq`, `my_last_read_seq`, `other_last_read_seq` | integer counters/cursors |
| `endpoints` | `{messages,send,read}` |

Use server-provided `composer.max_length` (hard cap 4000), `composer.images_max` (hard cap 10), `composer.enabled` and `read_only`; upload images via `composer.upload_endpoint` (`/api/v1/media`) and send the returned `med_...` references. `order.endpoint` navigates to buyer `/api/v1/orders/{ref}` or seller `/api/v1/sales/{ref}`.

### GET `/api/v1/conversations/{conversation}/messages` — cursor thread
| Query | Type | Validation |
|---|---|---|
| `before` | integer? | >=1, older messages with `seq < before` |
| `after` | integer? | >=0, prohibits `before` in same request; newer messages |
| `limit` | integer? | 1..configured `chat.page_size_max` (fallback 100); default configured `chat.page_size` (fallback 30) |

**200**: `data.conversation` (full header above), `data.messages[]` (oldest first), `meta.has_more_before`, `meta.has_more_after` (boolean), `meta.before_cursor` (integer/null), `meta.after_cursor` (integer), `meta.limit` (integer). For older pages pass `before=meta.before_cursor`; for refresh pass `after=meta.after_cursor`. Never combine `before` and `after`.

**`data.messages[]` schema:**
| Field | Type | Notes |
|---|---|---|
| `id`, `seq` | integer | Stable message ID and sequence cursor |
| `sent_at`, `time_label`, `day_key`, `day_label`, `starts_day` | ISO string, string, string, string, boolean | Day separator rendered by API |
| `type` | string | `message`, `system`, `notice` |
| `side`, `from_me` | string, boolean | `me`, `them`, or `system` |
| `code`, `text` | string/null | System code / text; text may be null for image-only messages |
| `images[]` | array | `{url: string|null, alt: string}`; empty when hidden/system |
| `hidden`, `masked`, `masked_note` | boolean, boolean, string/null | Moderation flags; do not expose hidden content |
| `read` | boolean/null | Only meaningful for own user messages |
| `client_id` | string/null, conditional | Included on own user messages; not on system messages |

### POST `/api/v1/conversations/{conversation}/messages` — send
| JSON field | Type | Validation |
|---|---|---|
| `text` | string/null | Optional; maximum **4000** characters hard cap; live lower cap from header |
| `images` | string[]/null | Optional; max **10** references hard cap; each matches `^med_[a-f0-9]{32}$`; live lower cap from header |
| `client_id` | string/null | Optional; max 64 chars; `^[A-Za-z0-9._:-]+$` |

Use a stable `client_id` for retry and optionally `Idempotency-Key` header. Empty-content and other business rules are enforced by the messaging service. **201** on newly created message; **200** for duplicate/replayed send. Both return `{data:{message:<message schema>,created:boolean,conversation:{id,last_seq,unread_count}}}`. Do **not** append a second bubble on `created:false`; reconcile by `client_id` or message `id`.

### POST `/api/v1/conversations/{conversation}/read` — mark read
No JSON body. Idempotent; route throttle **120 requests/minute**. **200** `{data:{changed:boolean,conversation_id:integer,unread_count:integer,last_read_seq:integer,unread_total:integer}}`.

### Errors and client behavior
- `404`: nonparticipant and nonexistent conversations intentionally look identical.
- Closed conversation business errors include `error.details.reason` and localized `error.details.banner`; switch composer to read-only and show banner.
- Chat message rule violations include `error.details.<field> = [localized message]`; some also include `error.details.kinds` array.
- Chat send rate-limit error includes `error.details.retry_after` seconds and HTTP `Retry-After` header; obey it before retrying.
- Form validation can reject `after` + `before` together, invalid media references, invalid client ID, and oversized text/images.
- Message image URLs are temporary signed URLs; refresh thread data when links expire.

Sources: [message limits](https://gitlab.com/alalmiyalhura/outlet/-/blob/main/modules/Chat/Domain/Message/MessageRules.php), [localized errors](https://gitlab.com/alalmiyalhura/outlet/-/blob/main/modules/Chat/Interfaces/Http/Middleware/LocalizeChatErrors.php). **Verification boundary:** source-code inspection only, not a live API response test; exact unread-counter subfields and generic error envelope still need independent verification.
