# Loan Aggregator Marketplace - API Documentation

Base URL: `http://localhost:5000/api/v1`  
Interactive Swagger UI: `http://localhost:5000/api/docs`  
OpenAPI Specification JSON: `http://localhost:5000/api/docs.json`  

---

## 1. Authentication & Session Management

All authenticated endpoints require an `Authorization: Bearer <access_token>` header or an active `loan_marketplace_refresh_token` HttpOnly cookie.

### `POST /auth/register`
Register a new borrower or lender user account.
- **Access:** Public
- **Body:**
  ```json
  {
    "email": "applicant@example.com",
    "password": "StrongPassword@123",
    "fullName": "Aarav Patel",
    "phoneNumber": "+919876543210",
    "role": "BORROWER" // "BORROWER" | "LENDER_ADMIN" | "LENDER_STAFF"
  }
  ```
- **Response (201):**
  ```json
  {
    "success": true,
    "message": "Account registered successfully. Please verify your email.",
    "data": {
      "userId": "uuid-v4",
      "email": "applicant@example.com",
      "fullName": "Aarav Patel",
      "role": "BORROWER",
      "status": "ACTIVE"
    }
  }
  ```

### `POST /auth/login`
Authenticate user with email and password. Issues short-lived access token and sets rotating refresh token in HttpOnly cookie.
- **Access:** Public (Rate limited)
- **Body:**
  ```json
  {
    "email": "applicant@example.com",
    "password": "StrongPassword@123"
  }
  ```
- **Response (200):**
  ```json
  {
    "success": true,
    "message": "Authentication successful.",
    "data": {
      "user": {
        "id": "uuid-v4",
        "email": "applicant@example.com",
        "fullName": "Aarav Patel",
        "role": "BORROWER",
        "lenderId": null
      },
      "accessToken": "jwt-token-string"
    }
  }
  ```

### `POST /auth/refresh`
Rotate refresh token and issue a fresh access token. Implements cryptographic family reuse detection.
- **Access:** Public (Extracts cookie or body)
- **Response (200):**
  ```json
  {
    "success": true,
    "message": "Session refreshed successfully.",
    "data": {
      "accessToken": "new-jwt-access-token"
    }
  }
  ```

### `POST /auth/logout`
Revoke active session tokens and clear authentication cookies.
- **Access:** Public / Authenticated

---

## 2. Marketplace & Calculators (Public)

### `GET /marketplace/categories`
Retrieve active loan categories.
- **Response (200):**
  ```json
  {
    "success": true,
    "data": [
      {
        "id": "uuid",
        "code": "PERSONAL_LOAN",
        "name": "Personal Loan",
        "description": "Unsecured personal financing...",
        "displayOrder": 1
      }
    ]
  }
  ```

### `GET /marketplace/products`
Query published loan products from verified partner lenders.
- **Query Parameters:** `category`, `lenderId`, `minAmount`, `maxAmount`, `tenureMonths`, `sortBy` (`rate`|`name`|`processingFee`), `sortOrder` (`asc`|`desc`), `page`, `limit`.
- **Response (200):** Paginated loan products array.

### `POST /marketplace/calculate-emi`
Compute reducing-balance monthly installment, total repayment, and interest.
- **Body:**
  ```json
  {
    "principal": 500000,
    "annualInterestRate": 10.5,
    "tenureMonths": 60
  }
  ```
- **Response (200):**
  ```json
  {
    "success": true,
    "data": {
      "principal": 500000,
      "annualInterestRate": 10.5,
      "tenureMonths": 60,
      "monthlyEMI": 10746.95,
      "totalRepayment": 644817,
      "totalInterest": 144817,
      "monthlyInterestRateDecimal": 0.00875
    }
  }
  ```

### `POST /marketplace/check-eligibility`
Evaluate indicative borrowing capacity based on Debt-To-Income (DTI), income thresholds, and age criteria.
- **Body:**
  ```json
  {
    "monthlyIncome": 75000,
    "existingMonthlyObligations": 15000,
    "requestedLoanAmount": 500000,
    "requestedTenureMonths": 48,
    "employmentType": "SALARIED",
    "age": 30
  }
  ```
- **Response (200):**
  ```json
  {
    "success": true,
    "data": {
      "isEligible": true,
      "scoreRatio": 1,
      "requestedAmount": 500000,
      "maxIndicativeBorrowingCapacity": 820000,
      "indicativeMaxEMI": 22500,
      "criteria": [
        {
          "criterion": "Minimum Monthly Income",
          "met": true,
          "actual": "₹75,000",
          "threshold": "₹25,000"
        }
      ],
      "disclaimer": "This is an indicative eligibility estimate based on initial financial parameters..."
    }
  }
  ```

### `POST /marketplace/compare-products`
Side-by-side comparison of 2 to 5 loan products.
- **Body:**
  ```json
  {
    "productIds": ["uuid-prod-1", "uuid-prod-2"],
    "requestedAmount": 1000000,
    "requestedTenureMonths": 60
  }
  ```

---

## 3. Borrower Management

### `GET /borrower/profile`
Retrieve current borrower details and financial profile.
- **Headers:** `Authorization: Bearer <token>`

### `PATCH /borrower/profile`
Update financial parameters (monthly income, existing commitments, address).
- **Headers:** `Authorization: Bearer <token>`

### `GET /borrower/applications`
Retrieve all applications created by the authenticated borrower.

---

## 4. Application Lifecycle

### `POST /applications`
Create a draft loan application.
- **Body:**
  ```json
  {
    "productId": "uuid-product-id",
    "requestedAmount": 500000,
    "requestedTenureMonths": 36,
    "loanPurpose": "Debt consolidation"
  }
  ```

### `POST /applications/:id/submit`
Submit application to partner lender. Validates required consents.
- **Body:**
  ```json
  {
    "consentTermsConfirmed": true,
    "consentCreditCheckConfirmed": true
  }
  ```

### `PATCH /applications/:id/status`
Transition status through the state machine:
`DRAFT` → `SUBMITTED` → `UNDER_REVIEW` → `ADDITIONAL_INFO_REQUIRED` → `IN_PROGRESS_WITH_LENDER` → `APPROVED` / `REJECTED` / `WITHDRAWN` / `CLOSED`
- **Body:**
  ```json
  {
    "status": "UNDER_REVIEW",
    "reason": "Preliminary documentation under review by credit officer."
  }
  ```

---

## 5. Document Management

### `POST /documents/upload-url`
Request signed upload URL for secure private document upload.
- **Body:**
  ```json
  {
    "applicationId": "uuid-app",
    "documentType": "INCOME_PROOF",
    "fileName": "salary_slip_sept.pdf",
    "fileSizeBytes": 2048500,
    "mimeType": "application/pdf"
  }
  ```

### `PUT /documents/upload?key=...&expires=...&sig=...`
Binary stream endpoint to write file to private storage. Validates HMAC signature.

### `POST /documents/complete-upload`
Complete upload and trigger magic byte file signature verification.

### `GET /documents/:id/download-url`
Generate short-lived signed download URL with tenant & borrower authorization checks.

---

## 6. Lender Portal (LENDER_ADMIN / LENDER_STAFF)

- `POST /lender/onboarding` - Submit lender organization registration.
- `GET /lender/profile` - Organization details & staff listing.
- `POST /lender/products` - Publish new loan product (with Version 1 entry).
- `PATCH /lender/products/:id` - Revise product rates, fees, or tenure with audit versioning.
- `GET /lender/applications` - View assigned applications (strictly isolated to lender tenant).

---

## 7. Commission Management & Admin

- `POST /commissions/rules` - Configure lender commission percentages or flat fees.
- `POST /commissions/disbursements` - Idempotently record lender verified disbursement milestone.
- `GET /commissions/ledger` - Immutable commission ledger entries.
- `GET /commissions/ledger/export` - Authorized CSV export.
- `GET /admin/dashboard` - Real-time metrics calculated from live database aggregates.
- `GET /admin/users` - User management & suspension controls.
- `GET /admin/lenders` - Lender onboarding review (Approve / Reject).
- `GET /admin/audit-logs` - Platform security and operational audit trail.

---

## 8. Integrations & Webhooks

### `GET /integrations/health`
Status of Mock Lender, Mock KYC, Mock Credit Bureau, and Notification adapters.

### `POST /integrations/webhook/lender`
Inbound status callback from institutional lenders.
- **Header:** `x-lender-signature: <hmac-sha256-signature>`
- **Body:**
  ```json
  {
    "eventId": "evt_unique_12345",
    "eventType": "APPLICATION_STATUS_UPDATE",
    "applicationId": "uuid-app",
    "newStatus": "APPROVED",
    "reason": "Lender credit committee approved sanction."
  }
  ```
