# System Architecture

## Overview

The Dubai Real Estate Marketplace is designed as a scalable, multi-tenant platform supporting 5 distinct user roles with granular access control.

## Database Architecture

### Core Design Principles
1. **Normalization**: 3NF for data integrity
2. **Partitioning**: Large tables (properties, leads) partitioned by date
3. **Indexing**: Strategic indexes on search/filter columns
4. **Soft Deletes**: `deleted_at` timestamps for data recovery
5. **Audit Logging**: Separate audit tables for compliance

### Entity Relationship Overview

```
users (1) ──── (N) user_roles (N) ──── (1) roles
    │
    ├── (1:N) properties (as agent/owner)
    ├── (1:N) leads (as assigned_agent)
    ├── (1:N) subscriptions
    └── (1:N) webinars

agencies (1) ──── (N) agency_agents ──── (N) users (agents)
    │
    ├── (1:N) agency_subscriptions
    └── (1:N) properties (via agents)

developers (1) ──── (N) projects (master communities)
    │
    └── (1:N) project_units (individual properties)

subscriptions (N) ──── (1) subscription_plans
    │
    └── (N) subscription_features

leads (N) ──── (1) properties
    ├── (N) lead_activities
    └── (N) lead_notes

webinars (1) ──── (N) webinar_registrations
    └── (N) webinar_properties (linked units)
```

## Scalability Strategy

### Horizontal Scaling
- **Read Replicas**: MySQL read replicas for property searches
- **Caching**: Redis for session, property listings, filters
- **CDN**: Static assets and property images
- **Load Balancer**: Multiple API instances

### Database Optimization
```sql
-- Partitioning example for leads table
CREATE TABLE leads (
    -- ... columns
) PARTITION BY RANGE (YEAR(created_at)) (
    PARTITION p2024 VALUES LESS THAN (2025),
    PARTITION p2025 VALUES LESS THAN (2026),
    PARTITION p_future VALUES LESS THAN MAXVALUE
);

-- Indexing strategy
CREATE INDEX idx_properties_search ON properties(
    status, property_type, completion_status, 
    price, area_sqft, location_id, is_active
);

-- Full-text search for property names/descriptions
CREATE FULLTEXT INDEX idx_properties_ft ON properties(name, description);
```

## Security Architecture

### Authentication & Authorization
1. **JWT Tokens**: Short-lived access tokens (15min), long-lived refresh tokens (7 days)
2. **Role-Based Access Control (RBAC)**: Middleware checks on all endpoints
3. **Resource-Level Permissions**: Users can only access their own resources
4. **API Rate Limiting**: 100 requests/minute per IP, 1000 per authenticated user

### Data Protection
- **Encryption at Rest**: MySQL TDE for sensitive tables
- **Encryption in Transit**: TLS 1.3 for all connections
- **PII Handling**: Encrypted storage for phone/emails in leads
- **Audit Logging**: All CRUD operations logged with user ID and timestamp

### Compliance
- **RERA Validation**: Automated permit number verification
- **Data Retention**: Automated purging of old data per UAE regulations
- **GDPR/UAE PDPL**: Data export and deletion capabilities

## Webime (Virtual Launch) Architecture

### Real-time Infrastructure
```
Webime Session
├── Socket.io room per webinar
├── Host controls (Developer/Agency)
├── Participant management
├── Screen sharing (WebRTC)
├── Live chat moderation
└── Property showcase carousel
```

### Webime Flow
1. **Scheduling**: Developer creates webinar, links to project
2. **Registration**: Customers register, receive unique link
3. **Live Session**: 
   - Host presents via video
   - Property 3D tour embedded
   - Real-time Q&A
   - Instant lead capture
4. **Recording**: Auto-save for replay
5. **Analytics**: Attendance, engagement metrics

## Lead Management Flow

```
Customer Inquiry
    ↓
Lead Created (status: NEW)
    ↓
Auto-Assignment Logic
    ├── Round-robin (Agency agents)
    ├── Skill-based (Property type expertise)
    └── Manual (Agency admin assigns)
    ↓
Agent Notification (Email + Push + SMS)
    ↓
Agent Follow-up
    ├── Status updates (CONTACTED, VIEWING, NEGOTIATING, CLOSED)
    ├── Activity logging (calls, meetings)
    └── Note taking
    ↓
Lead Scoring & Analytics
```

## Subscription & Billing

### Revenue Model
- **Freemium**: Basic listings free
- **Tiered Subscriptions**: Silver, Gold, Platinum for Agencies/Agents
- **Featured Listings**: Pay-per-highlight
- **Webime Hosting**: Per-session pricing

### Billing Flow
```
Subscription Selection
    ↓
Stripe Checkout Session
    ↓
Payment Confirmation Webhook
    ↓
Subscription Activation
    ↓
Feature Unlock (listing limits, analytics, etc.)
    ↓
Recurring Billing (monthly/annual)
```

## Performance Targets

- **Page Load**: < 2 seconds for property listings
- **Search Response**: < 500ms for filtered results
- **API Response**: < 200ms for authenticated endpoints
- **Concurrent Users**: 10,000+ simultaneous connections
- **Image Delivery**: < 100ms via CDN with lazy loading

## Monitoring & Observability

- **Application Metrics**: Prometheus + Grafana
- **Error Tracking**: Sentry integration
- **Performance**: New Relic APM
- **Uptime**: Pingdom/Statuspage
- **Database**: MySQL Performance Schema queries
