# Chat Module — Functions and Usage Guide

This document explains the purpose, inputs, outputs, and side effects of each function in the chat module.

Contents:
- ChatController (HTTP endpoints)
- ChatGateway (WebSocket events)
- ChatService (business logic)
- ChatAggregations (Mongo aggregation helpers)
- DTOs and Schemas (brief)

## ChatController — [src/chat/chat.controller.ts](helpmodulenestjs/src/chat/chat.controller.ts:0:0-0:0)

- createConnectionFromProfile(req: RequestDto, body: CreateConnection)
  - Route: POST `/create-connection`
  - Creates a 1-to-1 connection between the logged-in user and the target user.
  - Calls [ChatService.createConnections()](helpmodulenestjs/src/chat/chat.service.ts:58:4-78:5).
  - Auth: required.

- createGroup(req: RequestDto, body: CreateGroupDto)
  - Route: POST `/create-group`
  - Creates a group connection with provided name, image, and members (adds current user as admin).
  - Calls [ChatService.createGroup()](helpmodulenestjs/src/chat/chat.controller.ts:29:4-34:5).
  - Auth: required.

- groupDetails(req: RequestDto, _id: string)
  - Route: GET `/group-details/:_id`
  - Fetches group meta and current members for a connection (group).
  - Calls [ChatService.groupDetails()](helpmodulenestjs/src/chat/chat.controller.ts:40:4-42:5).
  - Auth: required.

- chatHis(req: RequestDto, queryData: ConnectionDto)
  - Route: GET `/list-connection`
  - Lists connections (normal/group, with unread counts and last message), supports:
    - search
    - pagination, limit
    - type filter: NORMAL | LOCKED | ARCHIVE
  - Calls `ChatService.listChatUsers()`.
  - Auth: required.

- getHistory(req: RequestDto, req_query: chatHistory)
  - Route: GET `/history`
  - Fetches chat/message history for a connection with optional cursor params.
  - Calls `ChatService.message_history()`.
  - Auth: required.

- messageDetails(req: RequestDto, _id: string)
  - Route: GET `/message/:_id`
  - Fetches a single message with populated relations.
  - Calls [ChatService.messageDetails()](helpmodulenestjs/src/chat/chat.service.ts:211:4-230:5).
  - Auth: required.

- connectionMuteUnmute(req: RequestDto, dto: MuteNotificationType)
  - Route: PATCH `/mute/unmute/`
  - Mutes or unmutes a connection for the logged-in user.
    - Types: HOUR | WEEK | ALWAYS
  - Calls [ChatService.muteOrUnmuteConnection()](helpmodulenestjs/src/chat/chat.service.ts:566:4-615:5).
  - Auth: required.

- markDelivered(req: RequestDto, message_id: string, user_id: string)
  - Route: PATCH `/delivered/:message_id/user_id/:user_id`
  - Marks a message as delivered for a specified user. Bridges HTTP to socket logic.
  - Calls [ChatGateway.deliveredMessage()](helpmodulenestjs/src/chat/chat.gateway.ts:511:4-577:5).
  - Auth: required.

- markRead(req: RequestDto, connection_id: string, user_id: string)
  - Route: PATCH `/read/:connection_id/user_id/:user_id`
  - Marks all messages in the connection as read by the specified user. Bridges HTTP to socket logic.
  - Calls [ChatGateway.readAllMessages()](helpmodulenestjs/src/chat/chat.gateway.ts:640:4-713:5).
  - Auth: required.

- groupOperations(req: RequestDto, body: GroupOperationsDto)
  - Route: PATCH `/operations`
  - Performs batch/group actions:
    - Exit group, exit+delete for me, clear chat
    - Lock/unlock/archive/unarchive/delete connections
    - Delete messages (for me/everyone)
    - Add/remove group members
    - Block/unblock users
    - Star/unstar messages, unstar all in connection
  - Calls [ChatService.groupOperations()](helpmodulenestjs/src/chat/chat.controller.ts:128:4-134:5).
  - Auth: required.

## ChatGateway — [src/chat/chat.gateway.ts](helpmodulenestjs/src/chat/chat.gateway.ts:0:0-0:0)

- handleConnection(socket)
  - Validates socket connection (auth), stores `user_data` on socket, emits a listening event.
  - Trigger: client connects.

- handleSendMessage(socket, payload: CreateConnection)
  - WS Event: `create_connection`
  - Creates a 1-to-1 connection and joins its room; emits `CREATE_CONNECTION_LISTENER` or error.
  - Calls [ChatService.createConnections()](helpmodulenestjs/src/chat/chat.service.ts:58:4-78:5).

- joinConnection(socket, payload: JoinConnection)
  - WS Event: `join_connection`
  - Joins a connection room by ID; emits `JOIN_CONNECTION` or error.

- leaveConnection(socket, payload: JoinConnection)
  - WS Event: `leave_connection`
  - Leaves a connection room; emits `LEAVE_CONNECTION` or error.

- typing(socket, payload: TypingDto)
  - WS Event: [typing](helpmodulenestjs/src/chat/chat.gateway.ts:111:4-130:5)
  - Broadcasts typing indicator for a user within a connection; emits `TYPING_EVENT_LISTEN`.

- sendMessage(socket, payload: SendMessageDto)
  - WS Event: `send_message`
  - Sends a text or media message (single or multiple) in a connection.
  - Enforces block rules for 1-to-1 connections, saves message(s), emits `SEND_MESSAGE`, and triggers notifications via [ChatService.messageNotifications()](helpmodulenestjs/src/chat/chat.service.ts:1234:4-1265:5).

- sendChatEmoji(socket, payload: SendChatEmoji)
  - WS Event: `send_chat_emoji`
  - Adds or removes an emoji reaction on a message:
    - Emits `MSG_REACTION_EMOJI` or `DELETE_MSG_REACTION_EMOJI`
    - May send push notifications

- readMessage(socket, payload: ReadMessage)
  - WS Event: `read_messages`
  - Marks either a single message (if `message_id` provided) or all messages in a connection as read.
  - Emits `READ_MESSAGE` events to senders.

- editMessage(socket, payload: EditMessageDto)
  - WS Event: `edit_message`
  - Edits a message authored by the current user and broadcasts `EDIT_MESSAGE`.

- EditMessage(socket, payload: { type, message_ids })
  - WS Event: `delete_message`
  - Deletes messages either for everyone (type == 1) or for me (else).
  - Emits `DELETE_MESSAGES` to the relevant room or user.

- forwardMessage(socket, payload: ForwardMessageDto)
  - WS Event: `forword_messages`
  - Forwards one or multiple messages to multiple connections, respecting block rules.
  - Emits `FORWARD_MESSAGE` and triggers notifications per connection.

- deliveredMessage(message_id: string, user_id: string)
  - Marks a message as delivered for a given user (and computes delivery status for group chats).
  - Emits `DELIVERED_MESSAGE` to the original sender.

- readSingleMessages(message_id: string, user_id: string)
  - Marks a single message as read for the user (ensures delivered first).
  - Emits `READ_MESSAGE` to sender.

- readAllMessages(connection_id: string, user_id: string)
  - Marks all messages in a connection as read for the user (ensures delivered first).
  - Emits `READ_MESSAGE` to each message sender.

- afterInit(server)
  - Called once when the gateway initializes.

- handleDisconnect(socket)
  - On socket disconnect, marks the user as offline via [ChatService.handleDisconnect()](helpmodulenestjs/src/chat/chat.gateway.ts:719:4-732:5) and emits `DISCONNECTING_SOCKET_ERROR` on failure.

## ChatService — [src/chat/chat.service.ts](helpmodulenestjs/src/chat/chat.service.ts:0:0-0:0)

Connection and user utilities:
- checkConnection(sent_by: string, sent_to: string)
  - Returns existing NORMAL connection between two users (both directions) or empty list.

- createConnections(user_id: string, payload: CreateConnection)
  - Validates IDs and returns an existing connection or creates a new one via [saveConnetions()](helpmodulenestjs/src/chat/chat.service.ts:80:4-96:5).

- saveConnetions(sent_by: string, sent_to: string)
  - Persists a NORMAL connection document with default arrays/flags, returns saved connection.

- getUser(user_id: string, projection: any)
  - Fetches a user with given projection for socket/UI enrichments.

Listing and history:
- listChatUsers(_id: string, search: string, type: string, pagination?: number, limit?: number)
  - Returns a paginated, faceted list of connections with:
    - unread counts
    - muted/archived/locked counts
    - last message summary
  - Uses [ChatAggregations](cci:2://file:///media/hf/Hard%20Disk/Documents/rahul_rana/helpmodulenestjs/src/chat/chat.aggregation.ts:4:0-1126:1) pipeline stages.

- message_history(user_id: string, req_query: chatHistory)
  - Fetches message history for a connection with optional cursor params.
  - Excludes soft-deleted messages for the user.

- message_history_query(query, user_id)
  - Assembles the aggregation pipeline used by `message_history()` including lookups (users, replies, emoji), grouping, pagination, and projections.

Message-level operations:
- messageDetails(message_id: string)
  - Fetches a single message with populated relations: `sent_by`, `sent_to`, `connection_id`, `reply_msg_id`.

- saveSingleMessage(sent_by, payload, user_connection_id?, sent_to_user_id?)
  - Persists a single message (TEXT/LINK/DOCUMENT/…).
  - Optionally overrides `connection_id` or `sent_to`.
  - Creates `ChatMedias` record for DOCUMENT/LINK types.
  - Returns populated message via [makeMsgResponse()](helpmodulenestjs/src/chat/chat.service.ts:500:4-540:5).

- saveMediasMessage(sent_by, payload, media, is_another_user_blocket_me)
  - Persists a message for a single media item; saves related ChatMedias entry.
  - Returns populated message via [makeMsgResponse()](helpmodulenestjs/src/chat/chat.service.ts:500:4-540:5).

- saveForwardMessage(connection_id, sent_by, messageData, is_another_user_blocket_me)
  - Persists a forwarded message into the target connection, with media handling (creates `ChatMedias` when applicable).
  - Returns populated message via [makeMsgResponse()](helpmodulenestjs/src/chat/chat.service.ts:500:4-540:5).

- editMessage(payload: EditMessageDto, user_id: string)
  - Edits message’s text if the current user is the author; marks `is_edited` and updates timestamps.
  - Returns updated message.

- deleteMessageForMe(user_id: string, message_ids: string[])
  - Soft-deletes messages for the user (adds user to `deleted_for` array).
  - Validates not already deleted.

- deleteMessageForEveryOne(user_id: string, message_ids: string[])
  - Soft-deletes the messages for all participants:
    - 1-to-1: both users
    - Group: all active members
  - Only the sender can perform this.

Delivery/read statuses and reactions:
- checkMuteOrUnmute(connection_id: string, sent_to: string)
  - Returns whether the connection is currently muted for the user (by expiry time).

- makeMsgResponse(_id: string)
  - Fetches a message by ID, populates relations, and aggregates emoji reactions into `message_emoji`.

- sendMessageNotification(sent_to: string, notification_data: any, is_muted: boolean, is_arvhived: boolean)
  - Sends push or silent push notification to all FCM tokens of the user based on mute/archive flags.

- muteOrUnmuteConnection(user_id: string, dto: MuteNotificationType)
  - Toggles mute for a connection (HOUR/WEEK/ALWAYS) by pushing/pulling an entry in `connection_muted_by`.

- starUnstarMessage(connection_id: ObjectId, message_ids: ObjectId[], user_id: string, type: string)
  - STARRED: add user to `starred_by`.
  - UNSTARRED: remove user from `starred_by` per message.
  - UNSTARRED_ALL: remove user from `starred_by` across the connection.

Group management:
- createGroup(req: RequestDto, body: CreateGroupDto)
  - Creates a group connection, sets the current user as admin, inserts all members, and returns group info.

- groupDetails(req: RequestDto, connection_id: string)
  - Returns group connection details and member list (excluding exited users).

- exitFromGroup(user_id: string, connection_id: string)
  - Exits a group. If the user is admin, promotes the next available member to admin.

- exitFromGroupAndDeleteChatForMe(user_id: string, connection_id: string)
  - Exits group, deletes connection for the user, and soft-deletes all messages for the user. Admin flow also promotes next admin.

- clearChatForParticularConnections(user_id: string, connection_id: string)
  - Clears (soft-deletes for the user) message history for a specific connection.
  - Validates membership in groups.

- lockMultipleConnections(user_id: string, connection_ids: string[])
  - Adds the user to `connection_locked_by` for multiple connections (validation included).

- unLockMultipleConnections(user_id: string, connection_ids: string[])
  - Removes the user from `connection_locked_by` for multiple connections (validation included).

- archiveMultipleConnections(user_id: string, connection_ids: string[])
  - Adds the user to `connection_archived_by` for multiple connections.

- unArchiveMultipleConnections(user_id: string, connection_ids: string[])
  - Removes the user from `connection_archived_by` for multiple connections.

- deleteMultipleConnections(user_id: string, connection_ids: string[], is_delete_chat: boolean)
  - Adds the user to `connection_deleted_by` and optionally soft-deletes all messages for the user.

- removeMemberFromGroup(user_id: string, user_ids: string[], connection_id: string)
  - Admin-only: Marks specified members as exited.

- addMemberInGroup(user_id: string, user_ids: string[], connection_id: string)
  - Admin-only: Adds or re-adds members to the group (upserts membership).

- blockUnBlockUser(loggerUserId: string, connectionId: string)
  - Toggles block/unblock between logged-in user and the target user.

- groupOperations(req: RequestDto, body: GroupOperationsDto)
  - Dispatcher for all grouped operations above. Returns a message describing the action performed.

Notifications and presence:
- messageNotifications(title, payload, from_user, connection_id, user_id, sent_to, message, fetchConnectionType, response_data)
  - Prepares notification payload and delegates to `sendMessageNotification()` respecting mute.

- handleDisconnect(token: string)
  - Verifies token and marks the user offline.

## ChatAggregations — [src/chat/chat.aggregation.ts](helpmodulenestjs/src/chat/chat.aggregation.ts:0:0-0:0)

These helpers produce MongoDB aggregation stages. Used by `listChatUsers()` and `message_history_query()`.

Core stages:
- match(query: any)
  - `$match` with provided query.

- matchData(user_id: string, groupConnectionIds: ObjectId[], type: string)
  - `$match` that selects connections for a user with respect to type filters (NORMAL | LOCKED | ARCHIVE) and soft-deleted exclusions.

- lookup_messages(user_id: string)
  - `$lookup` recent messages per connection excluding messages soft-deleted for the user.

- count_total_messages()
  - `$set` stage to compute `total_messages`.

- setData(user_id: string)
  - `$set other_user_id` to “the other side” of a 1-to-1 connection relative to the requesting user.

- lookupUser()
  - `$lookup` user profile (name, profile_pic, country_code, phone_no) for `other_user_id`.

- unwindData(value: string)
  - `$unwind` with `preserveNullAndEmptyArrays: true`.

- filterUsersByName(search: string)
  - `$redact` based on case-insensitive regex match on `fetch_users.name` or keeps all when search is empty.

- lookupUnreadChat(sent_to: string)
  - `$lookup` unread messages for the user per connection (excludes `deleted_for`).

- countMessageData()
  - `$set count_message` as size of `unread_chat`.

- findOtherUserId(_id: string)
  - Computes `other_user_id` based on whether the logged-in user is `sent_by` or `sent_to`.

- fetchMessages(user_id: string)
  - `$lookup` latest message for each connection and join the sender minimal profile.

- setLastMsg(_id: string)
  - Computes a user-friendly last message summary based on `message_type`.

Additional stages referenced and present:
- lookupForCheckMutedConnection(user_id)
- groupData()
- facetData(skip, limit)
- lookupSentBy(), unwindSentBy()
- lookupSentTo(), unwindSentTo()
- lookupReplyTo(), unwindReplyTo()
- lookupChatEmoji()
- groupDataForMessages(user_id)
- facetDataForMessage()
- projectData()

These support message history grouping, pagination, enrichment, and response shaping.

## DTOs — `src/chat/dto/`

- [chat.dto.ts](helpmodulenestjs/src/chat/dto/chat.dto.ts:0:0-0:0)
  - DTOs:
    - `RequestDto` (with `user_data`)
    - `CreateConnection`
    - `CreateGroupDto`
    - `GroupOperationsDto`
    - `paginationDto`
    - `ConnectionDto`
    - `chatHistory`
    - `BlockUserDto`
    - `MuteNotificationType`
  - Enums: `GroupOperations`, `connectionType`

- [socket.dto.ts](helpmodulenestjs/src/chat/dto/socket.dto.ts:0:0-0:0)
  - Socket payload shapes:
    - `SendMessageDto`
    - `EditMessageDto`
    - `ForwardMessageDto`
    - `JoinConnection`
    - `ReadMessage`
    - `TypingDto`
    - `SendChatEmoji`

## Schemas — `src/chat/schema/`

- [connections.schema.ts](helpmodulenestjs/src/chat/schema/connections.schema.ts:0:0-0:0)
  - Connection document (NORMAL/GROUP), sent_by/sent_to, group metadata, and arrays for archived/locked/deleted/muted state per user.

- [messages.schema.ts](helpmodulenestjs/src/chat/schema/messages.schema.ts:0:0-0:0)
  - Message document: connection, sent_by/to, media, status (SENT/DELIVERED/READ), `deleted_for`, `starred_by`, timestamps, etc.

- [media.schema.ts](helpmodulenestjs/src/chat/schema/media.schema.ts:0:0-0:0)
  - `ChatMedias` records created for messages containing media, including one-time media.

- [message.emoji.ts](helpmodulenestjs/src/chat/schema/message.emoji.ts:0:0-0:0)
  - `MsgReactions` mapping emoji to users per message.

- [group.members.schema.ts](helpmodulenestjs/src/chat/schema/group.members.schema.ts:0:0-0:0)
  - Group membership, roles (GROUP_ADMIN/MEMBER), join/exit times, flags like `is_exit_from_group`.

- [block.users.ts](helpmodulenestjs/src/chat/schema/block.users.ts:0:0-0:0)
  - Block relationships.