# Messaging Backend API - Work Record

## Task
Create messaging backend API routes for the Needyfy Next.js project.

## Files Created/Modified

### 1. `src/app/api/messages/route.ts` (Modified)
**GET /api/messages?userId=xxx** — Get conversations for a user
- Validates `userId` param (required, valid ID format)
- Verifies user exists in DB
- Fetches all messages involving the user with sender/receiver info
- Groups messages by "other user" in memory, keeping the most recent message per conversation
- Computes unread counts per conversation partner via separate query
- Returns sorted conversations (most recent first) with: `id`, `name`, `phone`, `avatar`, `lastMessage`, `lastMessageTime`, `unreadCount`

**POST /api/messages** — Send a message
- Rate limited (30 req/min)
- Validates required fields: `senderId`, `receiverId`, `content`
- Validates IDs, prevents self-messaging, content length (1-5000), message type
- Verifies both sender and receiver exist
- Creates message with sanitized content
- Returns created message with sender/receiver user info

### 2. `src/app/api/messages/[userId]/route.ts` (Created)
**GET /api/messages/[userId]?currentUserId=xxx&before=xxx&limit=50** — Get messages between two users
- Validates path param (`userId`) and query param (`currentUserId`)
- Validates optional cursor (`before`) and limit (1-100, default 50)
- Verifies both users exist
- Fetches messages between the two users, ordered by `createdAt` ASC
- Supports cursor-based pagination via `before` param (message ID → createdAt filter)
- Marks unread messages as read (batch update)
- Returns: `{ messages, hasMore, markedAsRead }` with sender info included

## Patterns Used
- Existing validation utilities (`isValidId`, `sanitizeString`, `isValidLength`, `isValidMessageType`)
- Existing rate limiting (`checkRateLimit`, `getRateLimitIdentifier`, `RATE_LIMITS`)
- Consistent error response format: `{ error: string }` with appropriate HTTP status codes
- Prisma `db` import from `@/lib/db`
- Follows project code style from `community/route.ts` and `notifications/route.ts`

## Verification
- ESLint: No errors in the new files
- Dev server: Running without compilation errors
- Manual API tests: All endpoints respond correctly with proper validation and error handling
