# API Architecture Documentation

## Base URL
```
Production: https://api.wilddubai.ae/v1
Development: http://localhost:3001/v1
```

## Authentication

### JWT Token Flow
```
POST /auth/login → { access_token, refresh_token }
Authorization: Bearer <access_token>
```

### Token Refresh
```http
POST /auth/refresh
Content-Type: application/json

{
  "refresh_token": "..."
}

Response:
{
  "access_token": "...",
  "expires_in": 900
}
```

## Core API Endpoints

### 1. Property Filtering API

#### Advanced Search
```http
GET /properties?search
Query Parameters:
  q                    - Search text (full-text on name/description)
  location_id          - Filter by location
  property_type_id     - Apartment, Villa, etc.
  listing_type         - sale | rent
  completion_status    - off_plan | ready | under_construction
  
  # Price Range (AED)
  price_min            - Minimum price
  price_max            - Maximum price
  price_per_sqft_min   - Min price per sqft
  price_per_sqft_max   - Max price per sqft
  
  # Property Details
  bedrooms             - Exact or min (e.g., 2 or 2+)
  bathrooms            - Exact or range
  area_sqft_min        - Minimum area
  area_sqft_max        - Maximum area
  
  # Dubai-Specific Filters
  developer_id         - Specific developer
  project_id           - Units within project
  is_off_plan          - true | false
  handover_before      - Date filter
  payment_plan         - true | false
  post_handover        - true | false
  
  # Amenities (comma-separated)
  amenities            - 1,3,5,7
  view_type            - sea,city,garden
  furnished            - unfurnished | semi | fully
  
  # Sorting
  sort_by              - price_asc | price_desc | date_desc | relevance
  
  # Pagination
  page                 - Page number (default: 1)
  limit                - Items per page (default: 20, max: 100)

Response:
{
  "data": [
    {
      "id": 12345,
      "title": "Luxury 2BR in Downtown Dubai",
      "slug": "luxury-2br-downtown-dubai",
      "price": 2500000,
      "price_formatted": "AED 2,500,000",
      "price_per_sqft": 1850,
      "listing_type": "sale",
      "completion_status": "ready",
      "property_type": "apartment",
      "bedrooms": 2,
      "bathrooms": 2.5,
      "area_sqft": 1350,
      "location": {
        "id": 45,
        "name": "Downtown Dubai",
        "slug": "downtown-dubai"
      },
      "images": [...],
      "agent": {
        "id": 789,
        "name": "Ahmed Hassan",
        "agency": "Dubai Prime Properties"
      },
      "rera_permit": "12345",
      "rera_verified": true,
      "is_featured": false,
      "created_at": "2024-01-15T10:30:00Z"
    }
  ],
  "meta": {
    "total": 1543,
    "page": 1,
    "limit": 20,
    "pages": 78,
    "facets": {
      "property_types": [...],
      "locations": [...],
      "price_ranges": [...],
      "completion_status": [...]
    }
  }
}
```

#### Map Search (Geo-based)
```http
GET /properties/map-search
Query:
  ne_lat, ne_lng       - Northeast bounds
  sw_lat, sw_lng       - Southwest bounds
  zoom                 - Map zoom level
  filters...           - Same as above

Response:
{
  "clusters": [
    {
      "count": 15,
      "lat": 25.2048,
      "lng": 55.2708,
      "price_range": { "min": 1200000, "max": 3500000 }
    }
  ],
  "properties": [...] // Individual pins at high zoom
}
```

#### Autocomplete/Suggestions
```http
GET /search/suggestions?q=downtown

Response:
{
  "locations": [
    { "id": 45, "name": "Downtown Dubai", "type": "area", "count": 1250 }
  ],
  "projects": [
    { "id": 123, "name": "Burj Vista", "developer": "Emaar", "count": 45 }
  ],
  "developers": [
    { "id": 5, "name": "Emaar Properties", "count": 342 }
  ]
}
```

### 2. Package Purchase & Payment APIs

#### List Subscription Plans
```http
GET /subscriptions/plans?target_role=agent

Response:
{
  "plans": [
    {
      "id": 1,
      "name": "Pro Agent",
      "slug": "pro-agent",
      "description": "Perfect for active agents",
      "price_monthly": 199,
      "price_annually": 1990,
      "currency": "AED",
      "savings_percent": 16,
      "features": {
        "max_listings": 20,
        "max_featured": 5,
        "analytics": true,
        "lead_management": true,
        "priority_support": true,
        "verified_badge": true
      },
      "is_popular": true
    }
  ]
}
```

#### Create Checkout Session
```http
POST /subscriptions/checkout
Authorization: Bearer <token>

Request:
{
  "plan_id": 2,
  "billing_cycle": "annual", // monthly | annual
  "success_url": "https://wilddubai.ae/payment/success?session_id={CHECKOUT_SESSION_ID}",
  "cancel_url": "https://wilddubai.ae/payment/cancel"
}

Response:
{
  "checkout_url": "https://checkout.stripe.com/pay/cs_test_...",
  "session_id": "cs_test_..."
}
```

#### Stripe Webhooks
```http
POST /webhooks/stripe
Headers:
  Stripe-Signature: <signature>

Events Handled:
- checkout.session.completed → Activate subscription
- invoice.paid → Renew subscription
- invoice.payment_failed → Mark past_due
- customer.subscription.deleted → Cancel subscription
- customer.subscription.updated → Update status/features

Processing:
1. Verify Stripe signature
2. Parse event payload
3. Idempotency check (using event.id)
4. Update subscription record
5. Send notification to user
6. Unlock/lock features based on status
```

#### Get Current Subscription
```http
GET /subscriptions/current
Authorization: Bearer <token>

Response:
{
  "subscription": {
    "id": 123,
    "plan": { ... },
    "status": "active",
    "billing_cycle": "annual",
    "current_period_ends": "2025-01-15T00:00:00Z",
    "trial_ends": null,
    "usage": {
      "listings_used": 12,
      "listings_limit": 20,
      "featured_used": 3,
      "featured_limit": 5
    },
    "features": [...],
    "invoices": [...]
  }
}
```

#### Upgrade/Downgrade
```http
POST /subscriptions/change-plan
Authorization: Bearer <token>

Request:
{
  "new_plan_id": 3,
  "proration_behavior": "create_prorations" // none | create_prorations
}

Response:
{
  "success": true,
  "effective_date": "2024-01-15T00:00:00Z",
  "invoice": { ... }, // If prorated charge due
  "new_features": { ... }
}
```

### 3. Lead Assignment Logic APIs

#### Get Leads (with filtering)
```http
GET /leads
Authorization: Bearer <token>
Query:
  status                 - new | contacted | qualified | ...
  priority               - low | medium | high | urgent
  assigned_to_me         - true | false
  source                 - direct_inquiry | webinar | ...
  date_from, date_to     - Date range
  property_id            - Leads for specific property

Response varies by role:
- Agent: Only assigned leads
- Agency Admin: All agency leads
- Developer: Leads from their webinars/projects
```

#### Create Lead (from inquiry)
```http
POST /leads
Authorization: Bearer <token> (optional for guests)

Request:
{
  "source_type": "direct_inquiry",
  "customer_name": "John Smith",
  "customer_email": "john@example.com",
  "customer_phone": "+971501234567",
  "unit_id": 12345,
  "notes": "Looking for a family home",
  "budget_min": 2000000,
  "budget_max": 3500000,
  "preferred_contact_method": "whatsapp"
}

Auto-Assignment Logic:
1. If unit_id provided → Assign to listing agent
2. If agent unavailable → Round-robin to agency team
3. If no agency → Assign based on location specialization
4. Send notification (email + push + SMS)
5. Create lead activity log

Response:
{
  "id": 456,
  "status": "new",
  "assigned_to": {
    "agent_id": 789,
    "agent_name": "Ahmed Hassan",
    "agency_name": "Dubai Prime Properties"
  },
  "estimated_response_time": "2 hours",
  "next_steps": ["Agent will contact you via WhatsApp"]
}
```

#### Manual Lead Assignment
```http
POST /leads/:id/assign
Authorization: Bearer <token> (Agency+ only)

Request:
{
  "agent_id": 789,
  "reason": "Agent has expertise in Downtown properties",
  "notify_agent": true
}

Validation:
- Agent must be in same agency
- Agent must have active subscription
- Agent listing count under limit

Response:
{
  "success": true,
  "assigned_at": "2024-01-15T14:30:00Z",
  "agent": { ... },
  "notification_sent": true
}
```

#### Update Lead Status
```http
PUT /leads/:id/status
Authorization: Bearer <token>

Request:
{
  "status": "contacted",
  "sub_status": "call_scheduled",
  "notes": "Spoke with customer, scheduled viewing for Saturday",
  "next_follow_up": "2024-01-20T10:00:00Z"
}

Status Pipeline:
new → contacted → qualified → viewing_scheduled → negotiating → offer_made → closed_won
                      ↓
              closed_lost / unresponsive

Response:
{
  "id": 456,
  "previous_status": "new",
  "current_status": "contacted",
  "updated_at": "2024-01-15T14:30:00Z",
  "next_action_required": "Viewing on Saturday, Jan 20"
}
```

#### Lead Activity Logging
```http
POST /leads/:id/activities
Authorization: Bearer <token>

Request:
{
  "activity_type": "call_made",
  "description": "Discussed requirements, customer wants 3BR in Marina",
  "duration_minutes": 15,
  "outcome": "qualified",
  "related_unit_id": 12345
}

Response:
{
  "id": 789,
  "lead_id": 456,
  "activity_type": "call_made",
  "performed_by": { ... },
  "created_at": "2024-01-15T14:30:00Z"
}
```

#### Get Lead Analytics
```http
GET /leads/analytics
Authorization: Bearer <token>

Response (Agent view):
{
  "summary": {
    "total_leads": 45,
    "new_this_month": 12,
    "converted": 8,
    "conversion_rate": 17.8,
    "avg_response_time": "1.5 hours"
  },
  "by_status": {
    "new": 5,
    "contacted": 12,
    "qualified": 8,
    "negotiating": 3,
    "closed_won": 15,
    "closed_lost": 2
  },
  "by_source": {
    "direct_inquiry": 20,
    "webinar": 15,
    "website": 10
  },
  "trend": [...] // Daily/weekly data
}

Response (Agency view - includes team):
{
  "team_summary": { ... },
  "agent_performance": [
    {
      "agent_id": 789,
      "agent_name": "Ahmed Hassan",
      "leads_assigned": 20,
      "leads_converted": 5,
      "conversion_rate": 25,
      "avg_response_time": "45 minutes"
    }
  ]
}
```

### 4. Project & Unit Management APIs

#### Developer Projects
```http
GET /dev/projects
POST /dev/projects
PUT /dev/projects/:id
DELETE /dev/projects/:id

Project Fields:
{
  "name": "Burj Vista",
  "description": "Luxury waterfront living...",
  "project_type": "residential",
  "total_units": 450,
  "completion_status": "under_construction",
  "completion_date": "2025-12-31",
  "location_id": 45,
  "amenities": [1, 3, 5, 7],
  "rera_permit_number": "BV-2023-001",
  "escrow_account": "1234567890",
  "images": [...],
  "floor_plans": [...]
}
```

#### Project Units
```http
GET /dev/projects/:id/units
POST /dev/units
PUT /dev/units/:id

Unit Fields (Off-Plan):
{
  "project_id": 123,
  "unit_number": "A-1205",
  "title": "2BR Apartment with Marina View",
  "property_type_id": 1,
  "bedrooms": 2,
  "bathrooms": 2,
  "area_sqft": 1250,
  "listing_type": "sale",
  "completion_status": "off_plan",
  "handover_date": "2025-12-31",
  "price": 2100000,
  "payment_plan": {
    "down_payment_percent": 10,
    "construction_percent": 40,
    "handover_percent": 10,
    "post_handover_percent": 40,
    "post_handover_months": 36
  },
  "images": [...],
  "floor_plan_url": "..."
}
```

### 5. Webime (Webinar) APIs

#### Schedule Webinar
```http
POST /dev/webinars
Authorization: Bearer <token> (Developer+)

Request:
{
  "title": "Downtown Dubai Luxury Launch",
  "description": "Exclusive preview of new waterfront residences",
  "scheduled_at": "2024-02-15T18:00:00+04:00",
  "duration_minutes": 90,
  "max_attendees": 500,
  "is_public": true,
  "properties": [
    { "unit_id": 123, "presentation_order": 1 },
    { "unit_id": 124, "presentation_order": 2 }
  ]
}

Response:
{
  "id": 789,
  "meeting_link": "https://meet.wilddubai.ae/wb-abc123",
  "registration_link": "https://wilddubai.ae/webinars/789/register",
  "calendar_invite": "...",
  "qr_code": "..."
}
```

#### Register for Webinar
```http
POST /webinars/:id/register
Authorization: Bearer <token> (or guest)

Request:
{
  "name": "John Smith",
  "email": "john@example.com",
  "phone": "+971501234567",
  "questions": "What are the payment plan options?"
}

Response:
{
  "registration_id": 456,
  "confirmation_email_sent": true,
  "calendar_invite_sent": true,
  "reminder_scheduled": true,
  "join_link": "https://meet.wilddubai.ae/wb-abc123?token=xyz"
}
```

#### Webinar Host Controls
```http
GET /dev/webinars/:id/dashboard    - Host control panel
POST /dev/webinars/:id/start       - Go live
POST /dev/webinars/:id/end         - End session
POST /dev/webinars/:id/attendees   - List attendees
GET /dev/webinars/:id/analytics    - Engagement stats
```

### 6. User Management APIs

#### Profile Management
```http
GET /me
PUT /me
PUT /me/password
PUT /me/avatar
DELETE /me
```

#### RERA Verification
```http
POST /me/verify-rera

Request:
{
  "rera_permit_number": "12345",
  "brn": "BRN-67890"
}

Response:
{
  "verification_status": "pending",
  "estimated_time": "24 hours",
  "reference_id": "VER-2024-001"
}
```

## Error Handling

### Standard Error Format
```json
{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "The request failed validation",
    "details": [
      {
        "field": "price",
        "message": "Price must be greater than 0"
      }
    ],
    "request_id": "req_abc123",
    "timestamp": "2024-01-15T14:30:00Z"
  }
}
```

### Error Codes
| Code | HTTP Status | Description |
|------|-------------|-------------|
| UNAUTHORIZED | 401 | Invalid or missing token |
| FORBIDDEN | 403 | Insufficient permissions |
| NOT_FOUND | 404 | Resource not found |
| VALIDATION_ERROR | 422 | Input validation failed |
| RATE_LIMITED | 429 | Too many requests |
| SUBSCRIPTION_REQUIRED | 403 | Feature requires subscription |
| SUBSCRIPTION_EXPIRED | 403 | Subscription has expired |
| QUOTA_EXCEEDED | 403 | Usage limit reached |

## Rate Limiting

```http
Headers:
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1640995200

Limits:
- Public endpoints: 100/minute per IP
- Authenticated: 1000/minute per user
- Property search: 200/minute per user
- Lead creation: 50/minute per user
- Webhook endpoints: 1000/minute per source
```

## Pagination Standard

```http
GET /properties?page=2&limit=20

Response:
{
  "data": [...],
  "pagination": {
    "page": 2,
    "limit": 20,
    "total": 1543,
    "pages": 78,
    "has_next": true,
    "has_prev": true,
    "next_page": 3,
    "prev_page": 1
  },
  "links": {
    "self": "/properties?page=2&limit=20",
    "first": "/properties?page=1&limit=20",
    "last": "/properties?page=78&limit=20",
    "next": "/properties?page=3&limit=20",
    "prev": "/properties?page=1&limit=20"
  }
}
```
