# Gold Wallet — Backend API Integration Contract

This contract defines the integration protocols, expected data structures, and security specifications agreed between the **Frontend (Next.js 15, React 19)** and **Backend (FastAPI, PostgreSQL)** teams.

---

## 1. Global Specifications

### Base URLs
- **Local Development:** `http://localhost:8000/api/v1`
- **Staging environment:** `https://staging-api.goldwallet.com/api/v1`
- **Production environment:** `https://api.goldwallet.com/api/v1`

### Protocols & Content Types
- **Transport:** HTTPS only (TLS 1.3 enforced in Staging & Production).
- **Format:** All request/response bodies must be encoded in `application/json`.
- **IP Address Telemetry:** The Frontend optionally sends `client_detected_ip` as telemetry; however, the Backend must rely on standard proxy headers (`X-Forwarded-For`, etc.) for absolute security verification.

---

## 2. Naming Conventions & Data Formats

### Case Formats
- **JSON Fields:** `snake_case` (e.g., `user_count`, `serial_number`).
- **HTTP Headers:** Standard kebab-case (e.g., `Authorization`, `X-Request-ID`).

### Date and Time Format
- **Standard:** ISO 8601 extended format with timezone information.
- **Example:** `2026-05-21T10:59:08.123Z` or `2026-05-21T11:00:00+03:00`.

### Decimal Handling (Money & Gold Weights)
> [!IMPORTANT]
> **No Floating Point Numbers for Financial Calculations:**
> All gold weight, price, balance, purity, and fee values must be transmitted as **strings** containing precise decimal representations. This avoids floating-point round-off issues in Javascript / Python.
>
> - **Incorrect:** `available_balance: 1000.55` (number)
> - **Correct:** `available_balance: "1000.55"` (string)

#### Standard Fields mapping:
- `gold_weight` / `available_grams` / `held_grams`: String (up to 4 decimal places). e.g., `"31.1035"`
- `unit_price` / `spot_price` / `buy_price` / `sell_price`: String (up to 2 decimal places). e.g., `"2645.50"`
- `total_amount` / `fees` / `spread`: String (up to 2 decimal places). e.g., `"250.00"`
- `purity`: String. e.g., `"99.99"`

---

## 3. Two-Stage Secure Authentication Flow

To meet the highest safety standards, authentication consists of two strict stages.

### Stage 1: Login Initiation
- **Endpoint:** `POST /api/v1/auth/login/initiate`
- **Request Body:**
  ```json
  {
    "username": "admin@goldwallet.com",
    "password": "StrongPassword123",
    "client_detected_ip": "185.123.45.10"
  }
  ```
- **Response Body (MFA required):**
  ```json
  {
    "requires_otp": true,
    "login_attempt_id": "8a31e8b4-02bf-4636-b183-bd93a7d5cb49",
    "otp_channel": "email",
    "masked_destination": "a***n@goldwallet.com",
    "expires_in_seconds": 120,
    "resend_available_after_seconds": 60,
    "message": "OTP verification required. Sent to email."
  }
  ```

### Stage 2: OTP Verification
- **Endpoint:** `POST /api/v1/auth/login/verify-otp`
- **Request Body:**
  ```json
  {
    "login_attempt_id": "8a31e8b4-02bf-4636-b183-bd93a7d5cb49",
    "otp_code": "739284"
  }
  ```
- **Response Body (Successful):**
  ```json
  {
    "access_token": "jwt_access_token_here",
    "refresh_token": "jwt_refresh_token_here",
    "token_type": "bearer",
    "user": {
      "id": "3a0b38c2-3cf9-42b7-84df-f2d4f20bf824",
      "name": "مدير النظام",
      "email": "admin@goldwallet.com",
      "role": "SUPER_ADMIN",
      "default_dashboard": "/admin/dashboard",
      "permissions": [
        "view_dashboard",
        "manage_users",
        "manage_wallets",
        "approve_transactions",
        "view_reports"
      ]
    }
  }
  ```

---

## 4. Standard Response Formats

### Pagination Format
All table lists use standard offset pagination.
- **Example Response:**
  ```json
  {
    "items": [],
    "total": 125,
    "page": 1,
    "page_size": 25,
    "pages": 5
  }
  ```

### Error Response Format (FastAPI Pydantic Standard)
All errors must return the following JSON object accompanied by the proper HTTP status code (e.g. 400, 401, 403, 404, 422, 500).
- **Example Validation Error (422 Unprocessable Entity):**
  ```json
  {
    "detail": "لقد أدخلت بيانات غير صالحة.",
    "code": "VALIDATION_ERROR",
    "field_errors": {
      "email": ["صيغة البريد الإلكتروني غير صالحة."]
    },
    "request_id": "f5e9276d-8cf2-47ef-bcf1-0e4ab91c8cfb"
  }
  ```

---

## 5. Security & Access Rules

1. **HttpOnly Cookies:** If the Backend supports issuing JWTs via secure `HttpOnly` cookie headers, it must provide a cookie named `token` (or matching standard) with `Secure`, `SameSite=Strict`, and `Path=/` parameters.
2. **Authorization Headers:** In case cookie-based transport is not used, the Frontend supports sending `Authorization: Bearer <access_token>` header on every request.
3. **Session Expiry:** A `401 Unauthorized` status must trigger immediate Frontend session clearance and redirection to the `/login` route.
4. **Permissions Check:** The Frontend dynamically hides interface elements/buttons based on the user's `permissions` array returned during OTP verification.

---

## 6. Open Questions for the Backend Team
- **CSRF Token:** Will the Backend issue a double-submit cookie or similar for CSRF protection when secure cookies are enabled? If so, what header name is preferred? (Default configured: `X-CSRF-Token`).
- **OTP Fallbacks:** What is the procedure if the email OTP channel fails? Will SMS or authenticator app (TOTP) fallbacks be supported in Stage 1?
- **Decimal Precision Limits:** What is the maximum decimal scale stored in the DB for the gold purity column? (Frontend currently assumes up to 4 decimal places).
