# Routing and Module Integration

This document describes the complete routing structure and module integration for the B2B Flight Ticketing UI application.

## Table of Contents

1. [Routing Structure](#routing-structure)
2. [Module Architecture](#module-architecture)
3. [Guards and Access Control](#guards-and-access-control)
4. [HTTP Interceptor Chain](#http-interceptor-chain)
5. [Application Initialization](#application-initialization)
6. [Lazy Loading Strategy](#lazy-loading-strategy)

## Routing Structure

The application uses Angular Router with lazy-loaded feature modules and role-based access control.

### Route Hierarchy

```
/
├── login (public)
├── unauthorized (public)
└── (authenticated routes - AuthGuard)
    ├── / → redirect to /dashboard
    ├── dashboard (all authenticated users)
    ├── booking (all authenticated users)
    │   ├── search
    │   ├── passenger-details
    │   └── payment
    ├── wallet (Finance_User, Agency_Admin)
    ├── reports (Agency_Admin)
    ├── admin (Super_Admin)
    ├── support (all authenticated users)
    └── ** → redirect to /dashboard
```

### Route Configuration

**Public Routes:**
- `/login` - Login page (no authentication required)
- `/unauthorized` - Unauthorized access page

**Protected Routes (AuthGuard):**
All routes under the root path require authentication:

- `/dashboard` - Dashboard overview (all authenticated users)
- `/booking` - Booking module with sub-routes (all authenticated users)
  - `/booking/search` - Flight search
  - `/booking/passenger-details` - Passenger details form
  - `/booking/payment` - Payment and confirmation
- `/wallet` - Wallet management (Finance_User, Agency_Admin roles)
- `/reports` - Sales reports and analytics (Agency_Admin role)
- `/admin` - Admin dashboard and KYC verification (Super_Admin role)
- `/support` - Support center and help resources (all authenticated users)

**Wildcard Route:**
- `**` - Redirects to `/dashboard`

## Module Architecture

The application follows Angular's recommended modular architecture:

### Core Module (`CoreModule`)

**Purpose:** Singleton services and global configuration

**Provides:**
- `AuthService` - Authentication and token management
- `ApiService` - Centralized HTTP client wrapper
- `NotificationService` - Real-time notifications via WebSocket
- HTTP Interceptors (TokenInterceptor, ErrorInterceptor)

**Import:** Only in `AppModule` (enforced by constructor check)

### Shared Module (`SharedModule`)

**Purpose:** Reusable components, directives, and pipes

**Exports:**
- Common Angular modules (CommonModule, FormsModule, ReactiveFormsModule)
- Angular Material components
- Shared UI components (LoadingSpinner, ErrorMessage, ConfirmationDialog, etc.)
- Custom directives and pipes

**Import:** In feature modules that need shared functionality

### Layout Module (`LayoutModule`)

**Purpose:** Application layout components

**Provides:**
- `HeaderComponent` - Top navigation bar with user info and notifications
- `SidebarComponent` - Side navigation menu with role-based filtering
- `MainLayoutComponent` - Main layout wrapper

**Export:** Layout components for use in app

### Feature Modules (Lazy-Loaded)

All feature modules are lazy-loaded via routing for optimal performance:

1. **AuthModule** (`/login`)
   - Login component and authentication flow

2. **DashboardModule** (`/dashboard`)
   - Dashboard overview with metrics and charts

3. **BookingModule** (`/booking`)
   - Flight search, passenger details, payment
   - Sub-routes configured within module

4. **WalletModule** (`/wallet`)
   - Wallet overview and transaction history
   - Top-up functionality

5. **ReportsModule** (`/reports`)
   - Sales reports and analytics
   - Export functionality

6. **AdminModule** (`/admin`)
   - Master admin dashboard
   - KYC verification queue

7. **SupportModule** (`/support`)
   - Support center and help resources
   - Ticket submission

## Guards and Access Control

### AuthGuard

**Purpose:** Verify user authentication

**Behavior:**
- Checks if user has valid JWT token
- Verifies token is not expired
- Redirects to `/login` if not authenticated
- Allows access if authenticated

**Applied to:** All routes under root path (except `/login` and `/unauthorized`)

### RoleGuard

**Purpose:** Verify user has required role(s)

**Behavior:**
- Checks if user has at least one of the required roles
- Required roles specified in route data: `data: { roles: ['Role1', 'Role2'] }`
- Redirects to `/unauthorized` if user lacks required role
- Allows access if user has required role

**Applied to:**
- `/wallet` - Requires Finance_User or Agency_Admin
- `/reports` - Requires Agency_Admin
- `/admin` - Requires Super_Admin

### Role Hierarchy

The application supports five roles:

1. **Super_Admin** - Platform administrator with access to all features
2. **Agency_Admin** - Agency administrator with access to reports and wallet
3. **Agent** - User who performs bookings
4. **Finance_User** - User with access to wallet management
5. **HR_User** - Human resources user

### Authorization Matrix

| Feature | Agency_Admin | Agent | Finance_User | HR_User | Super_Admin |
|---------|--------------|-------|--------------|---------|-------------|
| Dashboard | ✓ | ✓ | ✓ | ✓ | ✓ |
| Flight Search | ✓ | ✓ | ✗ | ✗ | ✓ |
| Booking | ✓ | ✓ | ✗ | ✗ | ✓ |
| Wallet Management | ✓ | ✗ | ✓ | ✗ | ✓ |
| Reports | ✓ | ✗ | ✗ | ✗ | ✓ |
| KYC Verification | ✗ | ✗ | ✗ | ✗ | ✓ |
| Master Dashboard | ✗ | ✗ | ✗ | ✗ | ✓ |
| Support Center | ✓ | ✓ | ✓ | ✓ | ✓ |

## HTTP Interceptor Chain

The application uses HTTP interceptors to handle cross-cutting concerns:

### Interceptor Order

1. **TokenInterceptor** (runs first)
   - Adds JWT token to Authorization header
   - Handles 401 responses with token refresh
   - Redirects to login if token refresh fails

2. **ErrorInterceptor** (runs second)
   - Handles HTTP errors globally
   - Maps error codes to user-friendly messages
   - Provides retry options for failed requests

### Configuration

Interceptors are configured in `CoreModule`:

```typescript
providers: [
  {
    provide: HTTP_INTERCEPTORS,
    useClass: TokenInterceptor,
    multi: true,
  },
  {
    provide: HTTP_INTERCEPTORS,
    useClass: ErrorInterceptor,
    multi: true,
  },
]
```

### Error Handling Strategy

- **400 (Bad Request):** Display validation errors on form fields
- **401 (Unauthorized):** Redirect to login
- **403 (Forbidden):** Show unauthorized message
- **404 (Not Found):** Show not found message
- **500 (Server Error):** Show generic error with retry option
- **Network Errors:** Show offline message

## Application Initialization

### Startup Sequence

1. **Angular Bootstrap** - `AppModule` is loaded
2. **Core Services Initialization** - Singleton services are created
3. **AppComponent Initialization** - Root component initializes
4. **Notification Service Connection** - WebSocket connection established (if authenticated)
5. **Routing** - Initial route is resolved and component loaded

### AppComponent Lifecycle

```typescript
ngOnInit() {
  // Initialize notification service if user is authenticated
  if (this.authService.isAuthenticated()) {
    this.notificationService.connect();
  }
}

ngOnDestroy() {
  // Clean up notification service connection
  this.notificationService.disconnect();
}
```

### NotificationService Initialization

The `NotificationService` is initialized on app startup to establish WebSocket connection for real-time notifications:

- Connects to backend WebSocket endpoint
- Listens for incoming notifications
- Updates notification badge count
- Displays toast notifications
- Handles reconnection on connection loss

## Lazy Loading Strategy

### Benefits

1. **Faster Initial Load** - Only load code needed for initial route
2. **Reduced Bundle Size** - Split code into smaller chunks
3. **On-Demand Loading** - Load feature modules when needed
4. **Better Performance** - Improved Time to Interactive (TTI)

### Implementation

Feature modules are lazy-loaded using dynamic imports:

```typescript
{
  path: 'booking',
  loadChildren: () =>
    import('./features/booking/booking.module').then((m) => m.BookingModule),
}
```

### Bundle Structure

After build, the application is split into:

- `main.js` - Core application code (AppModule, CoreModule, SharedModule, LayoutModule)
- `auth-module.js` - Auth feature module
- `dashboard-module.js` - Dashboard feature module
- `booking-module.js` - Booking feature module
- `wallet-module.js` - Wallet feature module
- `reports-module.js` - Reports feature module
- `admin-module.js` - Admin feature module
- `support-module.js` - Support feature module

### Preloading Strategy

Currently using default preloading (no preloading). Can be configured to preload all modules or use custom preloading strategy:

```typescript
RouterModule.forRoot(routes, {
  preloadingStrategy: PreloadAllModules
})
```

## Angular Material Theme

The application uses Angular Material with a custom theme configured in `styles/_theme.scss`:

- **Primary Color:** Blue (#1976d2)
- **Accent Color:** Orange (#ff9800)
- **Warn Color:** Red (#f44336)
- **Typography:** Roboto font family
- **Density:** Default (0)

Theme is applied globally to all Angular Material components.

## Testing the Routing

### Manual Testing

1. **Authentication Flow:**
   - Navigate to `/dashboard` without authentication → redirected to `/login`
   - Login with valid credentials → redirected to `/dashboard`
   - Navigate to protected routes → access granted

2. **Role-Based Access:**
   - Login as Agent → access to dashboard, booking, support
   - Try to access `/wallet` → redirected to `/unauthorized`
   - Login as Finance_User → access to wallet granted

3. **Lazy Loading:**
   - Open browser DevTools Network tab
   - Navigate to different routes
   - Observe separate bundle files being loaded on demand

### Automated Testing

Unit tests for guards and routing configuration are located in:
- `frontend/src/app/core/auth/auth.guard.spec.ts`
- `frontend/src/app/core/auth/role.guard.spec.ts`
- `frontend/src/app/app-routing.module.spec.ts`

## Troubleshooting

### Common Issues

1. **Circular Dependencies:**
   - Ensure CoreModule is only imported in AppModule
   - Use barrel exports (index.ts) carefully
   - Avoid importing feature modules in CoreModule

2. **Route Not Found:**
   - Check route path matches exactly (case-sensitive)
   - Verify lazy-loaded module exports RouterModule.forChild(routes)
   - Check wildcard route is last in configuration

3. **Guard Not Working:**
   - Verify guard is provided in CoreModule or root
   - Check guard is applied to route with canActivate
   - Ensure AuthService.isAuthenticated() returns correct value

4. **Interceptor Not Running:**
   - Verify interceptor is provided with HTTP_INTERCEPTORS token
   - Check multi: true is set
   - Ensure HttpClientModule is imported in CoreModule

## Requirements Validated

This routing and module integration validates the following requirements:

- **Requirement 1.3:** Protected route access control with AuthGuard
- **Requirement 1.5:** Role-based menu filtering and access control with RoleGuard
- **Requirement 11.1:** Notification service initialization on app startup
- **All Requirements:** Foundational infrastructure for all features

## Related Files

- `frontend/src/app/app-routing.module.ts` - Main routing configuration
- `frontend/src/app/app.module.ts` - Root module
- `frontend/src/app/app.component.ts` - Root component with initialization
- `frontend/src/app/core/core.module.ts` - Core module with services and interceptors
- `frontend/src/app/core/auth/auth.guard.ts` - Authentication guard
- `frontend/src/app/core/auth/role.guard.ts` - Role-based access guard
- `frontend/src/app/core/auth/token.interceptor.ts` - JWT token interceptor
- `frontend/src/app/core/interceptors/error.interceptor.ts` - Error handling interceptor
- `frontend/src/app/core/notification/notification.service.ts` - Notification service
