# LuckyChit API Documentation

## Base URL
```
http://localhost:3000/api
```

## Authentication
All protected endpoints require a JWT token in the Authorization header:
```
Authorization: Bearer <your-jwt-token>
```

## Test Credentials
- **Manager**: Mobile: `9876543210`, Password: `password123`
- **Member**: Mobile: `9876543211`, Password: `password123`

---

## Authentication Endpoints

### Signup (Public)
```
POST /auth/signup
```
**Request Body:**
```json
{
  "mobile_number": "9876543210",
  "full_name": "John Doe",
  "password": "password123",
  "email": "john@example.com",
  "address": "123 Main St",
  "emergency_contact": "9876543211"
}
```
**Required fields:** `mobile_number`, `full_name`, `password`

**Optional fields:** `email`, `address`, `emergency_contact`

**Response:**
```json
{
  "success": true,
  "message": "Account created successfully",
  "data": {
    "token": "eyJhbGciOiJIUzI1NiIs...",
    "user": {
      "id": "user-id",
      "mobile_number": "9876543210",
      "full_name": "John Doe",
      "email": "john@example.com",
      "role": "member",
      "is_active": true,
      "created_at": "2025-11-05T10:30:00.000Z",
      "updated_at": "2025-11-05T10:30:00.000Z"
    }
  }
}
```

### Login
```
POST /auth/login
```
**Request Body:**
```json
{
  "mobile_number": "9876543210",
  "password": "password123"
}
```
**Response:**
```json
{
  "success": true,
  "message": "Login successful",
  "data": {
    "token": "eyJhbGciOiJIUzI1NiIs...",
    "user": {
      "id": "user-id",
      "mobile_number": "9876543210",
      "full_name": "Test Manager",
      "role": "manager"
    }
  }
}
```

### Get Profile
```
GET /auth/profile
```
**Headers:** `Authorization: Bearer <token>`

### Update Profile
```
PUT /auth/profile
```
**Headers:** `Authorization: Bearer <token>`

### Change Password
```
PUT /auth/change-password
```
**Headers:** `Authorization: Bearer <token>`

### Create Member (Manager Only)
```
POST /auth/create-member
```
**Headers:** `Authorization: Bearer <token>`
**Request Body:**
```json
{
  "mobile_number": "9876543211",
  "full_name": "Test Member"
}
```

---

## Chit Group Management

### Create Chit Group (Manager Only)
```
POST /chit-groups
```
**Headers:** `Authorization: Bearer <token>`
**Request Body:**
```json
{
  "name": "Test Chit Group",
  "total_value": 100000,
  "monthly_installment": 5000,
  "duration_months": 20,
  "max_members": 20,
  "foreman_commission_percentage": 5,
  "draw_date": 15
}
```

### Get Manager's Chit Groups (Manager Only)
```
GET /chit-groups/manager?status=forming&page=1&limit=10
```
**Headers:** `Authorization: Bearer <token>`

### Get Member's Chit Groups
```
GET /chit-groups/member?status=active&page=1&limit=10
```
**Headers:** `Authorization: Bearer <token>`

### Get Chit Group Details
```
GET /chit-groups/{groupId}
```
**Headers:** `Authorization: Bearer <token>`

### Update Chit Group (Manager Only)
```
PUT /chit-groups/{groupId}
```
**Headers:** `Authorization: Bearer <token>`
**Request Body:**
```json
{
  "name": "Updated Chit Group Name",
  "foreman_commission_percentage": 6
}
```

### Delete Chit Group (Manager Only)
```
DELETE /chit-groups/{groupId}
```
**Headers:** `Authorization: Bearer <token>`

### Start Chit Group (Manager Only)
```
POST /chit-groups/{groupId}/start
```
**Headers:** `Authorization: Bearer <token>`

### Get Chit Group Statistics
```
GET /chit-groups/{groupId}/stats
```
**Headers:** `Authorization: Bearer <token>`

**Note:** Update and Delete operations only work for groups in 'forming' status. Once a group starts, it cannot be edited or deleted.

---

## Member Management

### Add Member to Group (Manager Only)
```
POST /members/{groupId}/members
```
**Headers:** `Authorization: Bearer <token>`
**Request Body:**
```json
{
  "mobile_number": "9876543211"
}
```

### Update Member Details (Manager Only)
```
PUT /auth/member/{memberId}
```
**Headers:** `Authorization: Bearer <token>`
**Request Body:**
```json
{
  "full_name": "Updated Name",
  "mobile_number": "9876543299",
  "email": "newemail@example.com",
  "address": "New Address",
  "emergency_contact": "9876543200"
}
```
**Note:** All fields are optional. Only provide fields you want to update.

### Remove Member from Group (Manager Only)
```
DELETE /members/{groupId}/members/{memberId}
```
**Headers:** `Authorization: Bearer <token>`

**Note:** Each member has a unique UUID identifier that never changes, even if name or phone number is updated.

### Get Group Members
```
GET /members/{groupId}/members?status=active&page=1&limit=20
```
**Headers:** `Authorization: Bearer <token>`

### Get Member Details
```
GET /members/{groupId}/members/{memberId}
```
**Headers:** `Authorization: Bearer <token>`

### Update Member Status (Manager Only)
```
PUT /members/{groupId}/members/{memberId}/status
```
**Headers:** `Authorization: Bearer <token>`
**Request Body:**
```json
{
  "status": "inactive"
}
```

### Get Member Payment Summary
```
GET /members/{groupId}/members/{memberId}/payment-summary
```
**Headers:** `Authorization: Bearer <token>`

---

## Payment Management

### Record Payment (Manager Only)
```
POST /payments
```
**Headers:** `Authorization: Bearer <token>`
**Request Body:**
```json
{
  "group_id": "group-id",
  "user_id": "user-id",
  "month": 9,
  "year": 2025,
  "amount": 5000,
  "payment_method": "upi",
  "transaction_id": "TXN123456",
  "notes": "Payment received via UPI"
}
```

### Get Group Payments
```
GET /payments/group/{groupId}?status=success&month=9&year=2025&page=1&limit=20
```
**Headers:** `Authorization: Bearer <token>`

### Get Member Payments
```
GET /payments/group/{groupId}/member/{memberId}?status=success&page=1&limit=20
```
**Headers:** `Authorization: Bearer <token>`

### Update Payment Status (Manager Only)
```
PUT /payments/{paymentId}/status
```
**Headers:** `Authorization: Bearer <token>`
**Request Body:**
```json
{
  "status": "success",
  "notes": "Payment confirmed"
}
```

### Get Group Payment Summary
```
GET /payments/group/{groupId}/summary
```
**Headers:** `Authorization: Bearer <token>`

### Get Pending Payments
```
GET /payments/group/{groupId}/pending
```
**Headers:** `Authorization: Bearer <token>`

---

## Monthly Draws Management

### Create Monthly Draw (Manager Only)
```
POST /monthly-draws
```
**Headers:** `Authorization: Bearer <token>`
**Request Body:**
```json
{
  "group_id": "group-uuid",
  "month": 3,
  "year": 2025,
  "client_seed": "user_provided_seed",  // Optional
  "winner_id": "member-uuid",           // Required for past draws
  "prize_amount": 195000,               // Optional
  "is_past_draw": true                  // Optional, for historical data
}
```

### Get Group Monthly Draws
```
GET /monthly-draws/group/{groupId}?status=completed&page=1&limit=20
```
**Headers:** `Authorization: Bearer <token>`

### Get Monthly Draw Details
```
GET /monthly-draws/{drawId}
```
**Headers:** `Authorization: Bearer <token>`

### Update Monthly Draw (Manager Only - NEW)
```
PUT /monthly-draws/{drawId}
```
**Headers:** `Authorization: Bearer <token>`
**Request Body:**
```json
{
  "winner_id": "new-winner-uuid",  // Optional
  "prize_amount": 195000,          // Optional
  "notes": "Corrected winner"      // Optional
}
```
**Use Case:** Fix mistakes in draw entry (wrong winner, wrong amount)

### Delete Monthly Draw (Manager Only - NEW)
```
DELETE /monthly-draws/{drawId}
```
**Headers:** `Authorization: Bearer <token>`
**Use Case:** Remove draw that was added by mistake

### Verify Draw Result
```
POST /monthly-draws/{drawId}/verify
```
**Headers:** `Authorization: Bearer <token>`
**Request Body:**
```json
{
  "client_seed": "optional-client-seed"
}
```

### Get Draw Statistics
```
GET /monthly-draws/group/{groupId}/statistics
```
**Headers:** `Authorization: Bearer <token>`

---

## WhatsApp Share Endpoints

### Share Payment Receipt
```
POST /share/payment-receipt
```
**Headers:** `Authorization: Bearer <token>`
**Request Body:**
```json
{
  "paymentId": "payment-id"
}
```
**Response:**
```json
{
  "success": true,
  "data": {
    "whatsappUrl": "https://wa.me/919876543210?text=...",
    "message": "🎉 Payment Successful!...",
    "recipient": {
      "name": "Member Name",
      "mobile": "9876543210"
    }
  }
}
```

### Share Draw Result
```
POST /share/draw-result
```
**Headers:** `Authorization: Bearer <token>`
**Request Body:**
```json
{
  "drawId": "draw-id",
  "recipientPhone": "9876543210"
}
```

### Share Group Invitation (Manager Only)
```
POST /share/group-invite
```
**Headers:** `Authorization: Bearer <token>`
**Request Body:**
```json
{
  "groupId": "group-id",
  "recipientPhone": "9876543210"
}
```

### Send Payment Reminder (Manager Only)
```
POST /share/payment-reminder
```
**Headers:** `Authorization: Bearer <token>`
**Request Body:**
```json
{
  "groupId": "group-id",
  "memberId": "member-id"
}
```

### Send Bulk Reminders (Manager Only)
```
POST /share/bulk-reminders
```
**Headers:** `Authorization: Bearer <token>`
**Request Body:**
```json
{
  "groupId": "group-id"
}
```
**Response:**
```json
{
  "success": true,
  "message": "Generated 5 reminder(s)",
  "data": {
    "total_reminders": 5,
    "reminders": [
      {
        "member": {
          "id": "member-id",
          "name": "John Doe",
          "mobile": "9876543210"
        },
        "whatsappUrl": "https://wa.me/..."
      }
    ]
  }
}
```

---

## Notification Management

### Get Notifications
```
GET /notifications?page=1&limit=20&type=payment_reminder&status=sent
```
**Headers:** `Authorization: Bearer <token>`

### Get Unread Count
```
GET /notifications/unread-count
```
**Headers:** `Authorization: Bearer <token>`
**Response:**
```json
{
  "success": true,
  "data": {
    "unread_count": 5
  }
}
```

### Mark Notification as Read
```
PUT /notifications/{notificationId}/read
```
**Headers:** `Authorization: Bearer <token>`

### Mark All as Read
```
PUT /notifications/read-all
```
**Headers:** `Authorization: Bearer <token>`

### Delete Notification
```
DELETE /notifications/{notificationId}
```
**Headers:** `Authorization: Bearer <token>`

### Get Notification Stats
```
GET /notifications/stats
```
**Headers:** `Authorization: Bearer <token>`

---

## Response Format

### Success Response
```json
{
  "success": true,
  "message": "Operation successful",
  "data": {
    // Response data
  }
}
```

### Error Response
```json
{
  "success": false,
  "message": "Error description"
}
```

### Paginated Response
```json
{
  "success": true,
  "data": {
    "items": [...],
    "pagination": {
      "currentPage": 1,
      "totalPages": 5,
      "totalItems": 100,
      "itemsPerPage": 20
    }
  }
}
```

---

## Status Codes

- `200` - Success
- `201` - Created
- `400` - Bad Request
- `401` - Unauthorized
- `403` - Forbidden
- `404` - Not Found
- `500` - Internal Server Error

---

## Data Models

### Chit Group Status
- `forming` - Group is being formed, members can be added
- `active` - Group is active and draws are happening
- `completed` - Group has completed all draws

### Member Status
- `active` - Member is active in the group
- `inactive` - Member is temporarily inactive
- `removed` - Member has been removed from the group

### Payment Status
- `pending` - Payment is pending
- `success` - Payment was successful
- `failed` - Payment failed
- `cancelled` - Payment was cancelled

### Payment Methods
- `upi` - UPI payment
- `bank_transfer` - Bank transfer
- `cash` - Cash payment
- `cheque` - Cheque payment

---

## Business Rules

1. **Chit Group Creation:**
   - Total value must equal monthly installment × duration months
   - Foreman commission must be between 0% and 20%
   - Draw date must be between 1 and 31

2. **Member Management:**
   - Members can only be added while group is in 'forming' status
   - Group must have at least 2 members to start
   - Members cannot be removed after group starts

3. **Payment Management:**
   - Payment amount must match monthly installment
   - Only one payment per member per month
   - Payments are automatically linked to member's total paid amount

4. **Access Control:**
   - Managers can manage their own groups only
   - Members can view groups they belong to
   - All operations require valid JWT token
