# PineHealth Backend Architecture

## System Architecture Diagram

```
┌─────────────────────────────────────────────────────────────────────┐
│                         Client Applications                          │
│                  (React Frontend, Mobile Apps, etc.)                 │
└────────────────────────────┬────────────────────────────────────────┘
                             │
                             │ HTTP/HTTPS Requests
                             │ (JSON + JWT Token)
                             ▼
┌─────────────────────────────────────────────────────────────────────┐
│                       Express.js Server                              │
│                      (Port 3000 / Custom)                            │
├─────────────────────────────────────────────────────────────────────┤
│  ┌─────────────────────────────────────────────────────────────┐   │
│  │                    Middleware Stack                          │   │
│  ├──────────────────────────────────────────────────────────────┤   │
│  │  • Helmet (Security Headers)                                 │   │
│  │  • CORS (Cross-Origin Resource Sharing)                      │   │
│  │  • Rate Limiter (DDoS Protection)                            │   │
│  │  • Body Parser (JSON/URL Encoded)                            │   │
│  │  • Morgan (HTTP Request Logger)                              │   │
│  │  • JWT Authentication                                        │   │
│  │  • Role Authorization                                        │   │
│  │  • Request Validation (Joi)                                  │   │
│  │  • File Upload (Multer)                                      │   │
│  │  • Error Handler                                             │   │
│  └──────────────────────────────────────────────────────────────┘   │
│                                                                       │
│  ┌─────────────────────────────────────────────────────────────┐   │
│  │                     Route Handlers                           │   │
│  ├──────────────────────────────────────────────────────────────┤   │
│  │  /api/auth/*    → authController (9 endpoints)               │   │
│  │  /api/user/*    → userController (11 endpoints)              │   │
│  │  /api/admin/*   → adminController (40+ endpoints)            │   │
│  │  /api/*         → publicController (10 endpoints)            │   │
│  └──────────────────────────────────────────────────────────────┘   │
│                                                                       │
│  ┌─────────────────────────────────────────────────────────────┐   │
│  │                    Business Logic Layer                      │   │
│  ├──────────────────────────────────────────────────────────────┤   │
│  │                      Controllers                             │   │
│  │  • Authentication (register, login, password reset)          │   │
│  │  • User Management (profile, orders, reviews, tickets)       │   │
│  │  • Public API (blog, doctors, departments, contact)          │   │
│  │  • Admin Operations (dashboard, CRUD for all resources)      │   │
│  └──────────────────────────────────────────────────────────────┘   │
│                                                                       │
│  ┌─────────────────────────────────────────────────────────────┐   │
│  │                    Utility Services                          │   │
│  ├──────────────────────────────────────────────────────────────┤   │
│  │  • JWT (token generation & verification)                     │   │
│  │  • Email (Nodemailer - transactional emails)                 │   │
│  │  • PDF (PDFKit - invoice generation)                         │   │
│  │  • Helpers (slug, pagination, validation)                    │   │
│  └──────────────────────────────────────────────────────────────┘   │
└────────────────────────────┬────────────────────────────────────────┘
                             │
                             │ Sequelize ORM
                             ▼
┌─────────────────────────────────────────────────────────────────────┐
│                         Data Access Layer                            │
│                        (Sequelize Models)                            │
├─────────────────────────────────────────────────────────────────────┤
│  • User, Post, Category, Tag, Page                                   │
│  • Doctor, Department, Product, Order                                │
│  • Review, Ticket, Contact, Setting                                  │
│  • Language, Coupon, Testimonial, Media                              │
│  • Comment, Subscriber                                               │
└────────────────────────────┬────────────────────────────────────────┘
                             │
                             │ MySQL Protocol
                             ▼
┌─────────────────────────────────────────────────────────────────────┐
│                      MySQL Database                                  │
│                   (Compatible with Laravel)                          │
├─────────────────────────────────────────────────────────────────────┤
│  Tables:                                                             │
│  users, posts, post_contents, categories, category_contents,         │
│  tags, taggables, pages, page_contents, doctors, doctor_contents,   │
│  departments, department_contents, products, product_contents,       │
│  product_categories, orders, order_items, reviews, tickets,         │
│  ticket_replies, contacts, settings, languages, coupons,            │
│  testimonials, testimonial_contents, media, comments, subscribers   │
└─────────────────────────────────────────────────────────────────────┘
```

## Request Flow

### 1. Authentication Flow

```
Client                    Server                   Database
  │                        │                          │
  ├─ POST /api/auth/login ─┤                          │
  │                        ├─ Validate request       │
  │                        ├─ Find user ─────────────▶│
  │                        │◀─ Return user ───────────┤
  │                        ├─ Compare password       │
  │                        ├─ Generate JWT token     │
  │◀─ Return token & user ─┤                          │
  │                        │                          │
  ├─ GET /api/user/profile ┤                          │
  │   (with token)         ├─ Verify JWT token       │
  │                        ├─ Extract user ID        │
  │                        ├─ Fetch user ────────────▶│
  │                        │◀─ Return user ───────────┤
  │◀─ Return user data ────┤                          │
```

### 2. CRUD Operation Flow

```
Client                    Server                   Database
  │                        │                          │
  ├─ POST /api/admin/posts┤                          │
  │   (with auth token)    ├─ Authenticate user      │
  │                        ├─ Authorize admin        │
  │                        ├─ Validate request       │
  │                        ├─ Generate slug          │
  │                        ├─ Create post ───────────▶│
  │                        │◀─ Return post ───────────┤
  │                        ├─ Create post content ───▶│
  │                        │◀─ Return content ────────┤
  │◀─ Return created post ─┤                          │
```

### 3. File Upload Flow

```
Client                    Server                   Filesystem/DB
  │                        │                          │
  ├─ POST /api/admin/media┤                          │
  │   (multipart form)     ├─ Authenticate           │
  │                        ├─ Validate file type     │
  │                        ├─ Check file size        │
  │                        ├─ Generate unique name   │
  │                        ├─ Save to disk ──────────▶│
  │                        │◀─ File saved ────────────┤
  │                        ├─ Create media record ───▶│
  │                        │◀─ Return record ─────────┤
  │◀─ Return file info ────┤                          │
```

## Component Relationships

```
┌─────────────────────┐
│      Routes         │
│   (auth, user,      │
│   admin, public)    │
└──────────┬──────────┘
           │ uses
           ▼
┌─────────────────────┐     ┌──────────────────┐
│    Controllers      │────▶│   Middleware     │
│  (Business Logic)   │     │ (auth, validate) │
└──────────┬──────────┘     └──────────────────┘
           │ uses
           ▼
┌─────────────────────┐     ┌──────────────────┐
│      Models         │────▶│    Utilities     │
│  (Data Access)      │     │ (jwt, email,pdf) │
└──────────┬──────────┘     └──────────────────┘
           │ queries
           ▼
┌─────────────────────┐
│     Database        │
│  (MySQL/MariaDB)    │
└─────────────────────┘
```

## Layer Responsibilities

### 1. Presentation Layer (Routes)
- **Purpose:** Define API endpoints and route requests
- **Files:** `src/routes/*.js`
- **Responsibilities:**
  - Map URLs to controller methods
  - Apply middleware to routes
  - Group related endpoints
  - Define route-level validation

### 2. Business Logic Layer (Controllers)
- **Purpose:** Implement application logic
- **Files:** `src/controllers/*.js`
- **Responsibilities:**
  - Process requests
  - Coordinate between models and utilities
  - Apply business rules
  - Format responses
  - Handle errors

### 3. Data Access Layer (Models)
- **Purpose:** Define data structure and relationships
- **Files:** `src/models/*.js`
- **Responsibilities:**
  - Define database schema
  - Define model relationships
  - Implement hooks (e.g., password hashing)
  - Provide data validation
  - Abstract database operations

### 4. Middleware Layer
- **Purpose:** Intercept and process requests
- **Files:** `src/middleware/*.js`
- **Responsibilities:**
  - Authenticate users (JWT verification)
  - Authorize access (role checking)
  - Validate input (Joi schemas)
  - Handle file uploads
  - Catch and format errors

### 5. Utility Layer
- **Purpose:** Provide reusable helper functions
- **Files:** `src/utils/*.js`
- **Responsibilities:**
  - Generate and verify JWT tokens
  - Send emails
  - Generate PDFs
  - Format data
  - Common operations

### 6. Configuration Layer
- **Purpose:** Manage application settings
- **Files:** `src/config/*.js`, `.env`
- **Responsibilities:**
  - Database configuration
  - Environment variables
  - Application constants

## Security Architecture

```
┌─────────────────────────────────────────────────────────────┐
│                      Security Layers                         │
├─────────────────────────────────────────────────────────────┤
│ Layer 1: Network Security                                    │
│  • CORS (Cross-Origin Resource Sharing)                      │
│  • Helmet (Security Headers)                                 │
│  • Rate Limiting (DDoS Prevention)                           │
├─────────────────────────────────────────────────────────────┤
│ Layer 2: Authentication                                      │
│  • JWT Token Verification                                    │
│  • Token Expiration                                          │
│  • Refresh Token Rotation                                    │
├─────────────────────────────────────────────────────────────┤
│ Layer 3: Authorization                                       │
│  • Role-Based Access Control                                 │
│  • Resource Ownership Verification                           │
│  • Permission Checking                                       │
├─────────────────────────────────────────────────────────────┤
│ Layer 4: Input Validation                                    │
│  • Joi Schema Validation                                     │
│  • SQL Injection Prevention (ORM)                            │
│  • XSS Prevention                                            │
│  • File Type Validation                                      │
├─────────────────────────────────────────────────────────────┤
│ Layer 5: Data Protection                                     │
│  • Password Hashing (bcrypt)                                 │
│  • Sensitive Data Filtering                                  │
│  • Environment Variable Encryption                           │
└─────────────────────────────────────────────────────────────┘
```

## Scalability Considerations

### Horizontal Scaling
```
┌───────────────┐
│ Load Balancer │
└───────┬───────┘
        │
   ┌────┴────┐
   │         │
   ▼         ▼
┌─────┐   ┌─────┐
│ App │   │ App │  (Multiple instances)
│ #1  │   │ #2  │
└──┬──┘   └──┬──┘
   │         │
   └────┬────┘
        │
        ▼
  ┌──────────┐
  │ Database │
  │ (Master) │
  └────┬─────┘
       │
   ┌───┴───┐
   │       │
   ▼       ▼
┌────┐   ┌────┐
│Read│   │Read│  (Read replicas)
│ #1 │   │ #2 │
└────┘   └────┘
```

### Caching Strategy
```
Client Request
     │
     ▼
┌─────────┐     Cache Hit    ┌───────┐
│  Redis  │◀─────────────────┤ Check │
│  Cache  │──────────────────▶Cache  │
└─────────┘     Cache Miss   └───────┘
     │                            │
     │                            ▼
     │                     ┌──────────┐
     └────────────────────▶│ Database │
                           └──────────┘
```

## Error Handling Flow

```
Request → Middleware → Controller → Model
                           │
                           ▼
                    ┌──────────────┐
                    │ Error Occurs │
                    └──────┬───────┘
                           │
                           ▼
                    ┌──────────────┐
                    │Express-Async │
                    │    Errors    │
                    └──────┬───────┘
                           │
                           ▼
                    ┌──────────────┐
                    │Error Handler │
                    │  Middleware  │
                    └──────┬───────┘
                           │
                           ▼
                    ┌──────────────┐
                    │  Format &    │
                    │  Log Error   │
                    └──────┬───────┘
                           │
                           ▼
                    Send Error Response
                    to Client
```

## Deployment Architecture

### Development
```
Developer Machine
  ├─ Node.js Server (localhost:3000)
  ├─ MySQL Database (localhost:3306)
  └─ React Frontend (localhost:8000)
```

### Production
```
Internet
  │
  ▼
┌─────────────┐
│   Nginx     │ (Reverse Proxy + SSL)
│   Port 443  │
└──────┬──────┘
       │
   ┌───┴────┐
   │        │
   ▼        ▼
┌─────┐  ┌─────┐
│ PM2 │  │ PM2 │  (Process Manager)
│ App │  │ App │
└──┬──┘  └──┬──┘
   │        │
   └───┬────┘
       │
   ┌───┴────┐
   │        │
   ▼        ▼
┌──────┐ ┌──────┐
│MySQL │ │Redis │
│ DB   │ │Cache │
└──────┘ └──────┘
```

## Technology Stack Summary

| Layer            | Technology      | Purpose                        |
|------------------|-----------------|--------------------------------|
| Runtime          | Node.js 14+     | JavaScript runtime             |
| Web Framework    | Express.js 4.x  | HTTP server & routing          |
| ORM              | Sequelize 6.x   | Database abstraction           |
| Database         | MySQL 5.7+      | Data persistence               |
| Authentication   | JWT             | Stateless auth tokens          |
| Validation       | Joi             | Request validation             |
| File Upload      | Multer          | Multipart form handling        |
| Email            | Nodemailer      | Email sending                  |
| PDF              | PDFKit          | PDF generation                 |
| Security         | Helmet          | Security headers               |
| CORS             | cors            | Cross-origin requests          |
| Password Hash    | bcryptjs        | Password encryption            |
| Logging          | Morgan          | HTTP request logging           |
| Process Manager  | PM2 (prod)      | Process management             |

## Conclusion

This architecture provides:
- ✅ Clear separation of concerns
- ✅ Scalable design
- ✅ Maintainable codebase
- ✅ Security best practices
- ✅ Production-ready infrastructure
- ✅ Easy testing and debugging
