# Task ID: 5
# Title: Implement, Document, & Test `readMessages` Endpoint
# Status: done
# Dependencies: 1
# Priority: high
# Description: Implement the `readMessages` method, write JSDoc/TSDoc documentation, and develop unit tests. Ensure adherence to SDK conventions for API calls, error handling, and authentication.
# Details:
Functional Requirement 4.4: Method: readMessages(session: string, chatId: string, options?: { messages?: number, days?: number }): Promise. API Call: POST /api/{session}/chats/{chatId}/messages/read. Parameters: session (path, required), chatId (path, required), messages (query, optional), days (query, optional). Response: ReadChatMessagesResponse object. Adhere to NFRs.

# Test Strategy:
Unit tests for marking messages as read by count, by days, handling responses, error scenarios, and parameter validation.

# Subtasks:
## 1. Implement Core `readMessages` Method Logic [done]
### Dependencies: None
### Description: Implement the `readMessages` method to interact with the `POST /{session}/chats/{chatId}/messages/read` API endpoint. This includes handling path parameters (`session`, `chatId`), optional query parameters (`messages`, `days`), and processing the `ReadChatMessagesResponse`.
### Details:
Focus on constructing the API request, correctly passing path and query parameters, making the POST request, and parsing the expected successful response structure (`ReadChatMessagesResponse`).
<info added on 2025-06-08T22:18:50.012Z>
Plan:
1. Define Method: Add `async readMessages(session: string, chatId: string, options?: ReadMessagesOptions): Promise<ReadChatMessagesResponse>` to `WasendClient` in `src/index.ts`.
2. Endpoint: `POST /${session}/chats/${chatId}/messages/read`.
3. Query Parameters: Handle `options.messages` and `options.days` as query parameters.
4. API Call: Use `this.httpClient.post<ReadChatMessagesResponse>(url, null, { params: queryParams })` (passing null as body since data is in query params).
5. Return: `response.data`.
6. Type Imports: Ensure `ReadMessagesOptions` and `ReadChatMessagesResponse` are imported from `./types/chat.types.ts`.
</info added on 2025-06-08T22:18:50.012Z>
<info added on 2025-06-08T22:20:31.196Z>
Successfully implemented the `readMessages` method in `src/index.ts`.
Key details of the implementation include: added `async readMessages(session: string, chatId: string, options?: ReadMessagesOptions): Promise<ReadChatMessagesResponse>` to `WasendClient`; uses endpoint `POST /${session}/chats/${chatId}/messages/read`; handles `options.messages` and `options.days` as query parameters; sends `null` as the request body; and imports `ReadMessagesOptions` and `ReadChatMessagesResponse` from `./types/chat.types.ts`.
</info added on 2025-06-08T22:20:31.196Z>

## 2. Integrate SDK-Standard Authentication Mechanisms [done]
### Dependencies: 5.1
### Description: Integrate the SDK's standard authentication mechanisms into the `readMessages` method to ensure all API calls are properly authenticated according to SDK conventions.
### Details:
Modify the core method implementation to include necessary authentication headers or tokens as required by the SDK's authentication strategy for API requests.
<info added on 2025-06-08T22:21:04.780Z>
The SDK-standard authentication (Bearer token via API key) is handled globally by the `this.httpClient` instance within the `WasendClient`. This `httpClient` is initialized in the constructor with the necessary Authorization header. Since the `readMessages` method uses `this.httpClient.post`, it will automatically include the standard authentication. Therefore, no specific code modifications are required within the `readMessages` method for authentication integration.
</info added on 2025-06-08T22:21:04.780Z>

## 3. Integrate SDK-Standard Error Handling [done]
### Dependencies: 5.1
### Description: Implement SDK-standard error handling within the `readMessages` method to manage API errors (e.g., 4xx, 5xx status codes) and other potential issues gracefully, translating them into SDK-specific errors.
### Details:
Enhance the core method to catch exceptions from the API call, interpret error responses, and throw or return standardized SDK error objects.
<info added on 2025-06-08T22:22:05.215Z>
Modify `readMessages` in `src/index.ts`. Add a `try...catch (error: any)` block around the `this.httpClient.post(...)` call. In the `catch` block, return a `ReadChatMessagesResponse` object: `{ success: false, message: error.response?.data?.message || error.message || 'Failed to read messages' }`. This approach aligns with the requirement to handle errors explicitly and fits the existing `ReadChatMessagesResponse` return type.
</info added on 2025-06-08T22:22:05.215Z>
<info added on 2025-06-08T22:23:21.694Z>
Successfully integrated SDK-standard error handling into the `readMessages` method in `src/index.ts`.
- Wrapped the `httpClient.post` call in a `try...catch (error: any)` block.
- In the `catch` block, the method now returns a `ReadChatMessagesResponse` with `success: false` and an error message derived from `error.response?.data?.message`, `error.message`, or a default string 'Failed to read messages'.
</info added on 2025-06-08T22:23:21.694Z>

## 4. Write JSDoc/TSDoc Documentation for `readMessages` [done]
### Dependencies: 5.1, 5.2, 5.3
### Description: Create comprehensive JSDoc/TSDoc documentation for the `readMessages` method. This includes documenting the method's purpose, its parameters (`session`, `chatId`, optional `messages`, optional `days`), the return type (`ReadChatMessagesResponse`), and any thrown exceptions.
### Details:
Ensure documentation is clear, accurate, and provides examples if applicable, covering all aspects of the method's usage and behavior.
<info added on 2025-06-08T22:23:49.379Z>
Plan for Subtask 5.4:
1. JSDoc Content for `readMessages`:
   - Method description: Marks messages in a specific chat as read.
   - @param session (string): The session identifier.
   - @param chatId (string): The ID of the chat (e.g., '1234567890@c.us' or '1234567890-1234567890@g.us').
   - @param options? (ReadMessagesOptions): Optional. Contains:
     - `messages?` (number): Number of latest messages to mark as read.
     - `days?` (number): Mark messages from the last N days as read.
   - @returns Promise<ReadChatMessagesResponse>: A promise resolving to an object indicating success or failure, with an optional message.
   - Note on errors: API or network errors will result in a response with `success: false` and an error message.
   - @example Basic usage example.
2. Execution:
   - Log this plan.
   - Set status to `in-progress`.
   - Add the JSDoc block to the `readMessages` method in `src/index.ts` (it already has a basic one, I will enhance it).
   - Log successful outcome.
   - Set status to `done`.
</info added on 2025-06-08T22:23:49.379Z>
<info added on 2025-06-08T22:24:37.835Z>
Completed enhancement of JSDoc/TSDoc for `readMessages` in `src/index.ts`. Key updates include: detailed description, parameter explanations (`session`, `chatId`, `options` with `messages`/`days`), return type (`Promise<ReadChatMessagesResponse>`), API/network error handling (`success: false`), and a comprehensive usage example.
</info added on 2025-06-08T22:24:37.835Z>

## 5. Develop Unit Tests for Success Scenarios [done]
### Dependencies: 5.1, 5.2, 5.3
### Description: Create unit tests to verify the correct functionality of the `readMessages` method in various success scenarios. This includes testing with the `messages` parameter (marking by count), the `days` parameter (marking by time range), and combinations thereof, ensuring valid `ReadChatMessagesResponse` is handled.
### Details:
Test cases should mock successful API responses and verify that the method processes these responses correctly and returns the expected outcome based on input parameters.
<info added on 2025-06-08T22:24:58.238Z>
Plan:
1. Test File: Add a new `describe` block for `readMessages` in `test/chats.test.ts`.
2. Mocking: Mock `mockedAxios.post`.
3. Test Cases (Success Scenarios for `readMessages`):
    - No options: `POST` to `/${session}/chats/${chatId}/messages/read` with `null` body and `undefined` params.
    - With `messages` option: `params` contains `messages`.
    - With `days` option: `params` contains `days`.
    - With both `messages` and `days` options: `params` contains both.
    - Return Value: Ensure method returns the mocked `ReadChatMessagesResponse` (e.g., `{ success: true, message: 'Messages marked as read' }`).
4. Execution Steps:
    a. Log plan.
    b. Set status `in-progress`.
    c. Add tests to `test/chats.test.ts`.
    d. Run `npx projen test`.
    e. If errors, debug and fix.
    f. Log outcome.
    g. Set status `done`.
</info added on 2025-06-08T22:24:58.238Z>
<info added on 2025-06-08T22:25:32.141Z>
Successfully developed and passed unit tests for the success scenarios of the `readMessages` method in `test/chats.test.ts`. The tests covered calls with no options, with the `messages` option, with the `days` option, and with both options. Verified that the correct API endpoint and parameters are used, and that the method returns the expected success response.
</info added on 2025-06-08T22:25:32.141Z>

## 6. Develop Unit Tests for Error Scenarios [done]
### Dependencies: 5.1, 5.2, 5.3
### Description: Create unit tests to verify the error handling capabilities of the `readMessages` method. This includes testing for API errors (e.g., 401, 403, 404, 500), invalid input parameters (e.g., incorrect types for `session`, `chatId`, `messages`, `days`), and authentication failures.
### Details:
Test cases should simulate various error conditions by mocking API error responses or providing invalid inputs, and assert that the method throws or returns the appropriate SDK-standard errors.
<info added on 2025-06-08T22:26:25.744Z>
Plan for Subtask 5.6:
1. Test File: Continue in `describe('readMessages', ...)` in `test/chats.test.ts`.
2. Mocking: Use `mockedAxios.post.mockRejectedValue(...)`.
3. Test Cases (Error Scenarios for `readMessages`):
    - Generic network error: Returns `{ success: false, message: 'Network error' }`.
    - API error (e.g., 401 with specific message): Returns `{ success: false, message: 'Specific API error message' }`.
    - API error (no `error.response.data.message`): Returns `{ success: false, message: error.message }`.
    - API error (no `error.response.data.message` or `error.message`): Returns `{ success: false, message: 'Failed to read messages' }`.
4. Execution Steps:
    a. Log plan.
    b. Set status `in-progress`.
    c. Add error scenario tests to `test/chats.test.ts`.
    d. Run `npx projen test`.
    e. If errors, debug and fix.
    f. Log outcome.
    g. Set status `done`.
</info added on 2025-06-08T22:26:25.744Z>
<info added on 2025-06-08T22:27:38.219Z>
Successfully developed and passed unit tests for the error scenarios of the readMessages method in test/chats.test.ts. Tests cover generic network errors, API errors with specific messages, API errors falling back to error.message, and API errors falling back to a default message. All tests confirm the method returns { success: false, message: ... } as expected.
</info added on 2025-06-08T22:27:38.219Z>

