> ## Documentation Index
> Fetch the complete documentation index at: https://docs.sagozen.digital/llms.txt
> Use this file to discover all available pages before exploring further.

# System Architecture

> High-level architecture, component interactions, and data flow diagrams

# System Architecture

## High-Level Architecture

```mermaid theme={null}
graph TB
    subgraph "CLIENT LAYER"
        WB[Web Browser Desktop/Tablet]
        MS[Mobile Safari iOS]
        MC[Mobile Chrome Android]
    end

    subgraph "CDN / LOAD BALANCER"
        CDN[CDN Static Content]
        LB[API Gateway / Load Balancer]
    end

    subgraph "APPLICATION LAYER"
        subgraph "Frontend Next.js :3000"
            AR[App Router /locale/]
            PAGES[Pages: Marketing, Dashboard, Auth]
            COMP[Components React 19]
            LIB[Client Library]
            STYLE[Tailwind CSS 4]
        end

        subgraph "Backend NestJS :3001"
            API[REST API Endpoints]
            CTRL[Controllers Auth, Booking, Services, Staff]
            SVC[Service Layer Business Logic]
            GUARD[Auth Guards & Middleware]
        end
    end

    subgraph "AUTHENTICATION"
        BA[Better Auth Service]
        OAUTH[OAuth Providers Google, GitHub]
        EMAIL[Email Service SMTP]
    end

    subgraph "DATA LAYER"
        PRISMA[Prisma ORM]
        PG[(PostgreSQL Database)]
    end

    WB --> CDN
    MS --> CDN
    MC --> CDN
    CDN --> AR

    WB --> LB
    MS --> LB
    MC --> LB
    LB --> API

    AR --> LIB
    PAGES --> COMP
    COMP --> STYLE
    LIB --> API

    API --> CTRL
    CTRL --> SVC
    CTRL --> GUARD
    SVC --> PRISMA
    GUARD --> BA

    BA --> OAUTH
    BA --> EMAIL
    PRISMA --> PG
```

## Component Interactions

### User Authentication Flow

```mermaid theme={null}
sequenceDiagram
    participant U as User
    participant F as Frontend
    participant BA as Better Auth
    participant B as Backend
    participant DB as Database

    U->>F: Opens application
    F->>BA: Check session
    alt Session invalid
        BA->>F: Redirect to login
        U->>F: Submit login form
        F->>B: POST /auth/login
        B->>DB: Query user record
        DB->>B: User data
        B->>B: Verify password bcrypt
        B->>DB: Create session
        DB->>B: Session saved
        B->>BA: Return token
        BA->>F: Store in cookie
        F->>U: Redirect to dashboard
    else Session valid
        F->>U: Show authenticated pages
    end

    U->>F: Click logout
    F->>B: POST /auth/logout
    B->>DB: Invalidate session
    B->>BA: Clear session
    BA->>F: Clear cookie
    F->>U: Redirect to login
```

### Booking Creation Flow

```mermaid theme={null}
sequenceDiagram
    participant C as Customer
    participant F as Frontend
    participant API as Backend API
    participant BS as BookingService
    participant DB as Database
    participant AUDIT as AuditLog

    C->>F: Browse services
    F->>API: GET /services
    API->>DB: Query services
    DB->>API: Service list
    API->>F: Return services
    F->>C: Display services

    C->>F: Submit booking form
    F->>API: POST /bookings
    API->>BS: Create booking
    BS->>BS: Validate pets & services
    BS->>BS: Check conflicts
    BS->>BS: Calculate pricing
    BS->>DB: Create Booking
    BS->>DB: Link BookingPet
    BS->>DB: Link BookingService
    DB->>BS: Booking created
    BS->>AUDIT: Log action
    BS->>API: Return booking
    API->>F: Booking confirmed
    F->>C: Show confirmation

    Note over BS,DB: Status: PENDING → CONFIRMED → IN_PROGRESS → COMPLETED
```

### Data Flow: Service Listing with i18n

```mermaid theme={null}
sequenceDiagram
    participant F as Frontend
    participant API as API Controller
    participant I as LanguageInterceptor
    participant S as ServiceService
    participant DB as Database
    participant T as i18n Utility

    F->>API: GET /services?lang=vi
    API->>I: Detect language
    I->>I: Check query param, header, cookie
    I->>API: Set lang = "vi"
    API->>S: findAll(lang)
    S->>DB: SELECT * FROM service
    DB->>S: Raw JSONB data
    S->>T: translateField(name, "vi")
    T->>T: Extract name.vi or fallback
    T->>S: Translated text
    S->>API: Localized services
    API->>F: JSON response
    F->>F: Render ServiceCard
```

## Database Schema Overview

### Entity Relationship Diagram

```mermaid theme={null}
erDiagram
    User ||--o{ Session : has
    User ||--o{ Account : has
    User ||--o{ Pet : owns
    User ||--o{ Booking : creates
    User ||--o| Staff : "is a"
    User ||--o{ AuditLog : generates

    Pet ||--o{ BookingPet : "booked in"
    Booking ||--o{ BookingPet : includes
    Booking ||--o{ BookingService : includes
    Booking }o--|| Staff : "assigned to"

    Service ||--o{ BookingService : "booked as"
    Service ||--o{ StaffService : "proficiency in"
    Staff ||--o{ StaffService : "skilled in"
    Staff ||--o{ Booking : manages

    User {
        string id PK
        string email UK
        string name
        enum role
        datetime createdAt
    }

    Pet {
        string id PK
        string ownerId FK
        string name
        string species
        json vaccinations
        text medicalHistory
    }

    Booking {
        string id PK
        string userId FK
        string staffId FK
        datetime startDate
        datetime endDate
        enum status
        decimal totalAmount
    }

    Service {
        string id PK
        jsonb name
        jsonb description
        enum category
        decimal basePrice
        string priceUnit
        boolean isActive
    }

    Staff {
        string id PK
        string userId FK
        string employeeCode
        string position
        enum status
        json workingHours
    }
```

### Key Table Relationships

**User & Authentication**

* User: Core user account
* Session: Active user sessions (1:N)
* Account: OAuth accounts (1:N)
* Verification: Email verification tokens

**Booking System**

* Booking: Main booking record
* BookingPet: Junction table (Booking N:N Pet)
* BookingService: Junction table (Booking N:N Service) with pricing
* Staff: Assigned staff member (optional)

**Multi-Language Support**

* Service.name: JSONB `{"en": "Grooming", "vi": "Chăm sóc lông"}`
* Service.description: JSONB with translations
* Staff position, specialization: JSONB fields
* Setting value: JSONB for multi-language configs

## API Design Patterns

### Standard Response Format

```json theme={null}
// Success Response
{
  "statusCode": 200,
  "message": "OK",
  "data": { /* resource data */ },
  "timestamp": "2024-01-15T10:30:00Z"
}

// Error Response
{
  "statusCode": 400,
  "message": "Bad Request",
  "error": "InvalidInput",
  "details": "Email is required",
  "timestamp": "2024-01-15T10:30:00Z"
}
```

### HTTP Status Codes

| Code                      | Usage                    |
| ------------------------- | ------------------------ |
| 200 OK                    | Successful GET/PUT/PATCH |
| 201 Created               | Successful POST          |
| 204 No Content            | DELETE success           |
| 400 Bad Request           | Invalid input            |
| 401 Unauthorized          | Missing/invalid auth     |
| 403 Forbidden             | Insufficient permissions |
| 404 Not Found             | Resource doesn't exist   |
| 409 Conflict              | Duplicate resource       |
| 500 Internal Server Error | Server error             |

### Resource Pagination

```typescript theme={null}
// Request
GET /bookings?page=1&limit=20&sortBy=createdAt&sortOrder=desc

// Response
{
  "statusCode": 200,
  "data": [ /* items */ ],
  "pagination": {
    "page": 1,
    "limit": 20,
    "total": 150,
    "totalPages": 8
  }
}
```

## Authentication & Authorization

### Better Auth Integration

* Session-based authentication
* JWT tokens for API access
* Refresh token rotation
* CSRF protection on state-changing operations
* Rate limiting on auth endpoints

### Role-Based Access Control (RBAC)

```
ADMIN (Full Access)
├─ All CRUD operations
├─ User & staff management
├─ Settings & configuration
└─ Audit log access

MANAGER (Limited Management)
├─ Booking management
├─ Staff scheduling
├─ Customer support
└─ Basic reporting

STAFF (Operational)
├─ View assigned bookings
├─ Update pet information
├─ Access customer notes
└─ No configuration access

CUSTOMER (Self-Service)
├─ Create/manage bookings
├─ Pet management
├─ View booking history
└─ No staff/config access
```

## Deployment Architecture

### Development Environment

```
localhost:3000 (Frontend Dev Server)
localhost:3001 (Backend Dev Server)
localhost:5432 (PostgreSQL)
```

### Production Environment

```mermaid theme={null}
graph TB
    CDN[CDN Static Assets Next.js, Images]
    LB[Load Balancer SSL/TLS, Routing]
    FE1[Frontend Instance 1]
    BE1[Backend Instance 1]
    PG[(PostgreSQL Primary)]
    BACKUP[(Backup DB Replica)]

    CDN --> LB
    LB --> FE1
    LB --> BE1
    BE1 --> PG
    PG -.replicate.-> BACKUP
```

## Security Architecture

### Network Security

* HTTPS/TLS 1.3+ for all communications
* CORS configured for specific origins
* Rate limiting per IP/endpoint
* DDoS protection via CDN

### Data Security

* Passwords hashed with bcrypt
* Sessions encrypted
* Sensitive data excluded from logs
* SQL injection prevention via ORM
* XSS prevention via React escaping

### Authentication Security

* Secure cookie flags (HttpOnly, Secure)
* CSRF tokens on state-changing operations
* Session timeout with warnings
* Account lockout after failed attempts
* Email verification for sign-up

## Scalability Considerations

### Current Architecture

* Monolithic backend suitable for \< 1000 bookings/day
* Single database instance with replication
* Static asset CDN for frontend

### Future Scaling

1. **Horizontal Scaling**: Multiple backend instances behind load balancer
2. **Database**: Query optimization, read replicas, eventual sharding
3. **Caching**: Redis for sessions and frequent queries
4. **Message Queue**: Async booking notifications and processing
5. **Microservices**: Separate booking, payment, notification services

***

## Related Documentation

<CardGroup cols={2}>
  <Card title="Installation Guide" icon="download" href="/installation">
    Set up development environment
  </Card>

  <Card title="API Reference" icon="code" href="/api-reference/introduction">
    Explore REST endpoints
  </Card>

  <Card title="Deployment Guide" icon="rocket" href="/deployment">
    Deploy to production
  </Card>

  <Card title="Back to Home" icon="home" href="/">
    Return to homepage
  </Card>
</CardGroup>
