# 01 - Message API & Echo Response Architecture

Welcome to **Milestone 1, Step 1.9**: Message API (`POST /api/v1/message`) and Echo Response flow.

---

## 1. Goal of Milestone 1.9

In M1.9, we connect the client widget UI to the backend through a simple HTTP message pipe.

At this stage, the backend intentionally does **NOT** use LLMs, AI, RAG, WebSockets, or a Rule Engine. It validates the active visitor session and returns an **Echo Response** (`"Echo: <User Message>"`).

```text
  [Widget UI]
       │
       │ 1. User types "Hello" & presses Enter / Click Send
       │ 2. Appends user message bubble to chat window
       │ 3. Sends POST /api/v1/message {"sessionId": "sess_...", "message": "Hello"}
       ▼
  [FastAPI Backend - app/routers/message.py]
       │
       │ 4. Validates that sessionId exists in MongoDB 'sessions' collection
       │ 5. Constructs echo reply: "Echo: Hello"
       ▼
  [Response: HTTP 200 OK]
  {"sessionId": "sess_...", "reply": "Echo: Hello"}
       │
       ▼
  [Widget UI]
       │ 6. Appends bot message bubble "Echo: Hello" & scrolls to bottom
```

---

## 2. Request and Response Schemas

### Request (`MessageRequest`):
```json
{
  "sessionId": "sess_8f3a1b9c4d2e",
  "message": "Hello"
}
```

### Response (`MessageResponse`):
```json
{
  "sessionId": "sess_8f3a1b9c4d2e",
  "reply": "Echo: Hello"
}
```

---

## 3. Session Validation in Backend

Before echoing the message, the endpoint calls `get_session_by_id(db, payload.sessionId)` against MongoDB:
- If the session exists $\rightarrow$ Returns `200 OK` with echo payload.
- If `sessionId` is invalid/unknown $\rightarrow$ Returns `404 Not Found`.
- If `message` is empty/missing $\rightarrow$ Pydantic returns `422 Unprocessable Entity`.

---

## 4. Client Widget UI Rendering

- **User Message (`.user-msg`):** Aligned right with blue background `#2563eb` and white text.
- **Bot Message (`.bot-msg`):** Aligned left with light gray background `#e2e8f0` and dark text.
- **Auto-Scroll:** `chatBody.scrollTop = chatBody.scrollHeight` ensures new messages are immediately visible.
- **Control Enablement:** Input field and send button are enabled only after a session is successfully initialized or restored.
