# Architecture Document
Generated: Tuesday, September 16, 2025

## System Overview
The Angular Clarity Boilerplate is a frontend-only, single-page application (SPA) template. It is designed to serve as a foundational starting point for developing enterprise-grade web applications. The system provides a pre-configured, modular, and scalable architecture using the Angular framework and is visually styled with the VMware Clarity Design System. Its primary purpose is to accelerate development by providing a structured and feature-rich starting point.

## Architecture Pattern
The boilerplate is built upon a **Component-Based Architecture**, which is fundamental to the Angular framework. The UI is composed of a tree of reusable and encapsulated components.

The overall architectural pattern follows best practices for scalable Angular applications, emphasizing a **Modular Design**. The application is segregated into a `CoreModule`, a `SharedModule`, and is designed for the addition of multiple `FeatureModules`. This structure promotes separation of concerns, reusability, and maintainability.

## Component Design (Frontend)

- **AppModule:** The root module of the application, responsible for bootstrapping the `AppComponent` and importing essential modules like the `CoreModule` and `AppRoutingModule`.

- **AppComponent:** The main application shell component. It contains the primary layout, including the Clarity header, sidebar navigation, and the main content area where routed components are displayed via `<router-outlet>`.

- **CoreModule:** This module is designed to be imported only once by the `AppModule`. It contains singleton services, route guards, and other one-time setup logic (e.g., HTTP interceptors). This pattern prevents services from being provided multiple times across the application.

- **SharedModule:** This module contains commonly used components, directives, and pipes that can be reused across different feature modules. It is imported by feature modules whenever they need access to these shared elements. It primarily exports common Angular modules (like `CommonModule`, `FormsModule`) and Clarity UI modules.

- **Feature Modules (Conceptual):** The architecture is designed for developers to create new feature modules (e.g., `DashboardModule`, `AdminModule`). These modules encapsulate all the components, services, and routing related to a specific business domain. They are typically **lazy-loaded** to improve initial application load performance.

## Data Architecture

### Primary Database
- Not applicable. As a frontend-only boilerplate, this project does not include a database. It is designed to connect to any backend with a data persistence layer.

### Data Model (Client-Side)
- Data models will be defined using **TypeScript interfaces or classes** within feature modules. These models will represent the structure of data objects retrieved from or sent to the backend API.
- **Example `User` model:**
  ```typescript
  export interface User {
    id: number;
    name: string;
    email: string;
    role: 'admin' | 'user';
  }

  Of course. Here is the architecture_document.md for the Angular Clarity boilerplate project, presented in a single code block for easy copying.

Markdown

# Architecture Document
Generated: Tuesday, September 16, 2025

## System Overview
The Angular Clarity Boilerplate is a frontend-only, single-page application (SPA) template. It is designed to serve as a foundational starting point for developing enterprise-grade web applications. The system provides a pre-configured, modular, and scalable architecture using the Angular framework and is visually styled with the VMware Clarity Design System. Its primary purpose is to accelerate development by providing a structured and feature-rich starting point.

## Architecture Pattern
The boilerplate is built upon a **Component-Based Architecture**, which is fundamental to the Angular framework. The UI is composed of a tree of reusable and encapsulated components.

The overall architectural pattern follows best practices for scalable Angular applications, emphasizing a **Modular Design**. The application is segregated into a `CoreModule`, a `SharedModule`, and is designed for the addition of multiple `FeatureModules`. This structure promotes separation of concerns, reusability, and maintainability.

## Component Design (Frontend)

- **AppModule:** The root module of the application, responsible for bootstrapping the `AppComponent` and importing essential modules like the `CoreModule` and `AppRoutingModule`.

- **AppComponent:** The main application shell component. It contains the primary layout, including the Clarity header, sidebar navigation, and the main content area where routed components are displayed via `<router-outlet>`.

- **CoreModule:** This module is designed to be imported only once by the `AppModule`. It contains singleton services, route guards, and other one-time setup logic (e.g., HTTP interceptors). This pattern prevents services from being provided multiple times across the application.

- **SharedModule:** This module contains commonly used components, directives, and pipes that can be reused across different feature modules. It is imported by feature modules whenever they need access to these shared elements. It primarily exports common Angular modules (like `CommonModule`, `FormsModule`) and Clarity UI modules.

- **Feature Modules (Conceptual):** The architecture is designed for developers to create new feature modules (e.g., `DashboardModule`, `AdminModule`). These modules encapsulate all the components, services, and routing related to a specific business domain. They are typically **lazy-loaded** to improve initial application load performance.

## Data Architecture

### Primary Database
- Not applicable. As a frontend-only boilerplate, this project does not include a database. It is designed to connect to any backend with a data persistence layer.

### Data Model (Client-Side)
- Data models will be defined using **TypeScript interfaces or classes** within feature modules. These models will represent the structure of data objects retrieved from or sent to the backend API.
- **Example `User` model:**
  ```typescript
  export interface User {
    id: number;
    name: string;
    email: string;
    role: 'admin' | 'user';
  }
Data Flow
API Call: A component's method calls a function in its corresponding service (e.g., userService.getUsers()).

Service Layer: The service uses Angular's HttpClient to make an HTTP request to the backend API.

Data Retrieval: The service receives the HTTP response and typically returns an Observable of the data, typed with the appropriate TypeScript interface.

Component Update: The component subscribes to the Observable. Once the data is received, it updates its local state, triggering Angular's change detection to re-render the template and display the new data.

API Design (Backend Communication)
This boilerplate is backend-agnostic. It is designed to communicate with any backend that exposes a RESTful or GraphQL API.

Communication Protocol
HTTP/HTTPS: Communication is handled via standard HTTP requests using Angular's HttpClient service.

Example Service Implementation
An example of a service making API calls:
// in user.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { User } from '../models/user.model';
import { environment } from '../../environments/environment';

@Injectable({
  providedIn: 'root'
})
export class UserService {
  private apiUrl = `${environment.apiBaseUrl}/users`;

  constructor(private http: HttpClient) { }

  getUsers(): Observable<User[]> {
    return this.http.get<User[]>(this.apiUrl);
  }

  getUserById(id: number): Observable<User> {
    return this.http.get<User>(`${this.apiUrl}/${id}`);
  }
}

Error Handling
HTTP interceptors can be provided in the CoreModule to handle API errors globally (e.g., logging errors, redirecting on 401 Unauthorized responses).

Security Architecture
Authentication: Authentication logic (e.g., handling JWTs, interacting with OAuth providers) should be encapsulated within an AuthService provided in the CoreModule.

Authorization (Route Guards): The architecture uses Angular's Route Guards to protect routes. An AuthGuard can be implemented to prevent unauthorized users from accessing certain parts of the application.

Client-Side Security: The boilerplate does not inherently protect against all client-side vulnerabilities. Developers should follow best practices for preventing XSS and CSRF attacks.

Scalability Considerations
Lazy Loading: The architecture strongly encourages the use of lazy-loaded feature modules. This ensures that the initial application bundle size remains small, leading to faster load times. As new features are added, they do not impact the initial load performance.

Modular Design: The strict separation of concerns into Core, Shared, and Feature modules makes the codebase easier to manage, test, and scale as the application grows in complexity.

State Management: For applications with complex state, a state management library like NgRx or Akita can be easily integrated into this architecture without requiring significant refactoring.

---

## ARCHITECTURE UPDATE - 2025-09-26 09:59:41



# Architecture Document
Generated: 2025-09-26T09:44:40.087454

## System Overview - Weather Application Extension
Building upon the existing Angular Clarity Boilerplate, this system extends its capabilities to a fully functional Weather Application. The architecture comprises a responsive Angular frontend, a dedicated backend proxy service, and integration with an external third-party weather API. The frontend, built with Angular and Clarity Design System, handles user interactions, displays current weather and multi-day forecasts. The backend proxy, developed with Node.js and Express.js, acts as a secure intermediary, managing API keys, abstracting external API complexities, and enabling data caching to enhance performance and scalability. This setup ensures a robust, secure, and performant weather information delivery system.

## Architecture Pattern - Client-Server with API Gateway/Proxy
To fulfill the requirements of integrating an external API securely and efficiently, the system adopts a **Client-Server Architecture** with a prominent **API Gateway/Proxy Pattern** for the backend:

*   **Frontend (Client):** The Angular application serves as the client, responsible for the user interface, presentation logic, and making API requests to the backend proxy.
*   **Backend Proxy (API Gateway):** A dedicated lightweight service (Node.js/Express.js) sits between the frontend and the external weather API. Its responsibilities include:
    *   **Security:** Protecting the external weather API key by not exposing it to the client-side.
    *   **Abstraction:** Providing a single, consistent set of API endpoints to the frontend, decoupling it from the external API's specifics.
    *   **Data Transformation:** Mapping external API responses to a standardized format consumed by the frontend.
    *   **Performance:** Implementing caching mechanisms (e.g., Redis) to store frequently requested weather data, reducing redundant external API calls and improving response times (NFR-001, NFR-005).
    *   **Rate Limiting:** Managing requests to the external API to comply with usage policies (Business Rule 2).
    *   **Error Handling:** Centralized handling of external API failures before responses are sent to the frontend (FR-007, NFR-004).
*   **External Weather API:** A third-party service (e.g., OpenWeatherMap) provides the raw weather data.

This pattern enhances security, simplifies frontend development by providing a consistent interface, and improves scalability and reliability through caching and centralized error management.

## Component Design - Weather Application

### Frontend (Angular) Components:
Building upon the existing modular structure (FR-002, FR-003, FR-004):
*   **`AppModule`**: The root module, handling application bootstrapping and core layout. Imports `CoreModule` and `SharedModule`.
*   **`CoreModule`**: Contains singleton services and `HttpInterceptors` for global concerns.
    *   `WeatherApiService`: Handles all HTTP requests to the backend proxy for weather data.
    *   `UnitConversionService`: Manages temperature unit conversion logic and state (Celsius/Fahrenheit).
    *   `ErrorHandlerInterceptor`: Intercepts and processes global API errors, displaying user-friendly messages (FR-007).
    *   `GeolocationService`: Wraps browser's Geolocation API to fetch user's location (FR-003).
*   **`SharedModule`**: Contains reusable UI components, directives, and pipes.
    *   `LoadingSpinnerComponent`: Generic spinner for data loading states (FR-006).
    *   `ErrorAlertComponent`: Displays general error messages (FR-007).
    *   `TemperatureUnitToggleComponent`: A UI component (e.g., toggle switch) for switching between Celsius/Fahrenheit (FR-005).
*   **`WeatherFeatureModule` (Lazy-Loaded):** Encapsulates all weather-specific functionality.
    *   `WeatherPageComponent`: Main smart component orchestrating data flow, integrating search, current weather, and forecast displays.
    *   `LocationSearchComponent`: Contains the search input field and trigger for geolocation (FR-002, FR-003).
    *   `CurrentWeatherCardComponent`: Displays current weather conditions (temperature, description, humidity, wind) for a location (FR-001). Utilizes Clarity Card component.
    *   `ForecastListComponent`: Displays the multi-day forecast (FR-004). May use Clarity List or multiple Clarity Card components.
    *   `WeatherIconComponent`: Displays appropriate weather icons based on conditions.

### Backend (Node.js/Express.js Proxy) Components:
*   **`server.js` (or `app.ts`):** Main entry point, sets up Express app, middleware (CORS, body-parser), and registers routes.
*   **`routes/weatherRoutes.js`:** Defines API endpoints for weather data (`/api/current-weather`, `/api/forecast`) and maps them to controller functions (FR-008).
*   **`controllers/weatherController.js`:** Handles incoming requests, validates input, interacts with `WeatherService`, and sends responses.
*   **`services/weatherService.js`:** Core business logic.
    *   Calls the `ExternalWeatherApiClient`.
    *   Performs data transformation/normalization from external API response to internal models.
    *   Interacts with `CacheService` for data caching (NFR-005, Business Rule 3).
*   **`clients/externalWeatherApiClient.js`:** Specific client for making HTTP requests to the chosen external weather API (e.g., using `axios` or `node-fetch`). Handles API key injection from environment variables (NFR-002, Business Rule 1).
*   **`services/cacheService.js`:** Abstracts Redis interactions for caching weather data.
*   **`config/env.js`:** Manages environment variables for API keys and other configurations.

## Data Architecture

### Frontend (TypeScript Interfaces):
Data models on the frontend will be defined using TypeScript interfaces to ensure strong typing and data consistency, aligning with the `requirements_document.md` Data Requirements section.
```typescript
// src/app/shared/models/location.model.ts
export interface Location {
  name: string;
  country?: string; // Optional, as some APIs might only provide city
  latitude: number;
  longitude: number;
}

// src/app/shared/models/current-weather.model.ts
export interface CurrentWeather {
  location: Location;
  temperature: number;
  unit: 'Celsius' | 'Fahrenheit';
  condition: string;
  description: string;
  icon: string; // URL or icon code
  humidity: number;
  windSpeed: number;
  timestamp: number; // Unix timestamp or ISO string
}

// src/app/shared/models/forecast-day.model.ts
export interface ForecastDay {
  location: Location;
  date: string; // ISO date string, e.g., 'YYYY-MM-DD'
  tempHigh: number;
  tempLow: number;
  unit: 'Celsius' | 'Fahrenheit';
  condition: string;
  description: string;
  icon: string; // URL or icon code
}
```

### Backend (Data Transformation & Caching):
*   The backend proxy will receive raw data from the external weather API and transform it into the `CurrentWeather` and `ForecastDay` models defined above before sending it to the frontend.
*   **Caching Database (Redis):** Redis will be used as an in-memory data store for caching weather data (NFR-005, Business Rule 3). Cache keys will be constructed based on location (city, latitude/longitude) and unit, with a configurable time-to-live (TTL) to ensure data freshness while reducing external API calls. For example, a key could be `weather:london:celsius:current` or `weather:london:fahrenheit:forecast`.

## API Design - Backend Proxy Endpoints

The backend proxy will expose RESTful API endpoints, allowing the frontend to fetch weather data. All responses will be in JSON format.

*   **Base URL:** `/api`
*   **Endpoints (FR-008):**
    *   `GET /api/current-weather?location={city}[&lat={latitude}&lon={longitude}][&units={metric|imperial}]`
        *   **Description:** Retrieves current weather conditions for a specified location (city name or geographic coordinates).
        *   **Parameters:**
            *   `location`: (Required if `lat` and `lon` are not provided) City name (e.g., `London`).
            *   `lat`: (Optional, with `lon`) Latitude for geolocation search.
            *   `lon`: (Optional, with `lat`) Longitude for geolocation search.
            *   `units`: (Optional) `metric` (Celsius, m/s) or `imperial` (Fahrenheit, miles/hour). Defaults to `metric`.
        *   **Response (200 OK):** `CurrentWeather` object.
        *   **Error Responses:** 400 Bad Request (invalid parameters), 404 Not Found (location not found), 500 Internal Server Error (external API issue).

    *   `GET /api/forecast?location={city}[&lat={latitude}&lon={longitude}][&units={metric|imperial}]`
        *   **Description:** Retrieves a multi-day weather forecast for a specified location.
        *   **Parameters:** Same as `/api/current-weather`.
        *   **Response (200 OK):** An array of `ForecastDay` objects.
        *   **Error Responses:** Same as `/api/current-weather`.

## Security Architecture

*   **API Key Management (NFR-002, Business Rule 1):** External weather API keys will be stored as environment variables on the backend server and never committed to version control or exposed to the client-side. The backend proxy will inject these keys into its requests to the external API.
*   **HTTPS (NFR-002):** All communication between the Angular frontend and the Node.js/Express.js backend proxy, and ideally between the proxy and the external weather API (if supported), will use HTTPS/SSL to ensure data encryption in transit.
*   **Input Validation (Business Rule 4, NFR-002):** Both frontend and backend will perform input validation on user-provided location data to prevent injection attacks or invalid requests. The backend proxy will sanitize and validate all parameters before forwarding them to the external weather API.
*   **CORS Configuration:** The Express.js backend will be configured with appropriate Cross-Origin Resource Sharing (CORS) headers to allow requests only from the Angular frontend's domain, preventing unauthorized cross-origin requests.
*   **Error Handling:** The backend will avoid exposing sensitive internal error details to the client. Generic, user-friendly error messages will be returned instead (FR-007).

## Scalability Considerations

*   **Frontend Scalability:** Angular's default build optimizations (tree-shaking, minification, lazy loading of feature modules) ensure efficient client-side performance. The modular architecture facilitates independent development and scaling of features.
*   **Backend Scalability (NFR-005):**
    *   **Containerization (Docker):** The Express.js backend service will be containerized using Docker, allowing for easy deployment and orchestration in cloud environments (e.g., Kubernetes, AWS Fargate, Azure Container Instances).
    *   **Horizontal Scaling:** The stateless nature of the backend proxy (apart from caching) enables horizontal scaling, where multiple instances can run concurrently behind a load balancer to handle increased request load.
    *   **Caching (Redis):** Implementing Redis caching significantly reduces the load on the external weather API and improves response times, especially for frequently requested locations, thereby enhancing throughput and scalability (NFR-001, NFR-005, Business Rule 3).
    *   **External API Rate Limiting (Business Rule 2):** The backend proxy will implement mechanisms to respect the external weather API's rate limits, potentially queueing or throttling requests to avoid service interruptions.
*   **Reliability (NFR-004):** The backend will incorporate retry mechanisms with exponential backoff for transient failures when communicating with the external weather API. Circuit breakers can be considered for more resilient handling of persistent external API outages.



---

## ARCHITECTURE UPDATE - 2025-09-26 10:00:22


# Architecture Document
Generated: 2025-09-26T09:44:40.087454

## System Overview - Weather Application Extension
Building upon the existing Angular Clarity Boilerplate, this system extends its capabilities to a fully functional Weather Application. The architecture comprises a responsive Angular frontend, a dedicated backend proxy service, and integration with an external third-party weather API. The frontend, built with Angular and Clarity Design System, handles user interactions, displays current weather and multi-day forecasts. The backend proxy, developed with Node.js and Express.js, acts as a secure intermediary, managing API keys, abstracting external API complexities, and enabling data caching to enhance performance and scalability. This setup ensures a robust, secure, and performant weather information delivery system.

## Architecture Pattern - Client-Server with API Gateway/Proxy
To fulfill the requirements of integrating an external API securely and efficiently, the system adopts a **Client-Server Architecture** with a prominent **API Gateway/Proxy Pattern** for the backend:

*   **Frontend (Client):** The Angular application serves as the client, responsible for the user interface, presentation logic, and making API requests to the backend proxy.
*   **Backend Proxy (API Gateway):** A dedicated lightweight service (Node.js/Express.js) sits between the frontend and the external weather API. Its responsibilities include:
    *   **Security:** Protecting the external weather API key by not exposing it to the client-side (NFR-002, Business Rule 1).
    *   **Abstraction:** Providing a single, consistent set of API endpoints to the frontend, decoupling it from the external API's specifics (FR-008).
    *   **Data Transformation:** Mapping external API responses to a standardized format consumed by the frontend.
    *   **Performance:** Implementing caching mechanisms (e.g., Redis) to store frequently requested weather data, reducing redundant external API calls and improving response times (NFR-001, NFR-005, Business Rule 3).
    *   **Rate Limiting:** Managing requests to the external API to comply with usage policies (Business Rule 2).
    *   **Error Handling:** Centralized handling of external API failures before responses are sent to the frontend (FR-007, NFR-004).
*   **External Weather API:** A third-party service (e.g., OpenWeatherMap) provides the raw weather data.

This pattern enhances security, simplifies frontend development by providing a consistent interface, and improves scalability and reliability through caching and centralized error management.

## Component Design - Weather Application

### Frontend (Angular) Components:
Building upon the existing modular structure (FR-002 from base boilerplate, FR-003 from base boilerplate) and incorporating new weather features:
*   **`AppModule`**: The root module, handling application bootstrapping and core layout. Imports `CoreModule` and `SharedModule`.
*   **`CoreModule`**: Contains singleton services and `HttpInterceptors` for global concerns (FR-002 from base boilerplate, Business Rule: Singleton services).
    *   `WeatherApiService`: Handles all HTTP requests to the backend proxy for weather data (FR-001, FR-004, FR-008).
    *   `UnitConversionService`: Manages temperature unit conversion logic and state (Celsius/Fahrenheit) (FR-005).
    *   `ErrorHandlerInterceptor`: Intercepts and processes global API errors, displaying user-friendly messages (FR-007, NFR-004).
    *   `GeolocationService`: Wraps browser's Geolocation API to fetch user's location (FR-003).
*   **`SharedModule`**: Contains reusable UI components, directives, and pipes (FR-002 from base boilerplate, Business Rule: Reusable components).
    *   `LoadingSpinnerComponent`: Generic spinner for data loading states (FR-006).
    *   `ErrorAlertComponent`: Displays general error messages (FR-007).
    *   `TemperatureUnitToggleComponent`: A UI component (e.g., toggle switch) for switching between Celsius/Fahrenheit (FR-005).
    *   `WeatherIconComponent`: Displays appropriate weather icons based on conditions (FR-001, FR-004).
*   **`WeatherFeatureModule` (Lazy-Loaded):** Encapsulates all weather-specific functionality (FR-002 from base boilerplate, Business Rule: Lazy-loaded modules).
    *   `WeatherPageComponent`: Main smart component orchestrating data flow, integrating search, current weather, and forecast displays.
    *   `LocationSearchComponent`: Contains the search input field and trigger for geolocation, adhering to Clarity Design (FR-002, FR-003, Interface Requirements: Search Bar).
    *   `CurrentWeatherCardComponent`: Displays current weather conditions (temperature, description, humidity, wind) for a location, utilizing Clarity Card component (FR-001, Interface Requirements: Weather Card).
    *   `ForecastListComponent`: Displays the multi-day forecast, potentially using Clarity List or multiple Clarity Card components (FR-004, Interface Requirements: Forecast List).

### Backend (Node.js/Express.js Proxy) Components:
*   **`server.js` (or `app.ts`):** Main entry point, sets up Express app, middleware (CORS, body-parser), and registers routes.
*   **`routes/weatherRoutes.js`:** Defines API endpoints for weather data (`/api/current-weather`, `/api/forecast`) and maps them to controller functions (FR-008).
*   **`controllers/weatherController.js`:** Handles incoming requests, validates input (Business Rule 4), interacts with `WeatherService`, and sends responses.
*   **`services/weatherService.js`:** Core business logic.
    *   Calls the `ExternalWeatherApiClient`.
    *   Performs data transformation/normalization from external API response to internal models.
    *   Interacts with `CacheService` for data caching (NFR-005, Business Rule 3).
*   **`clients/externalWeatherApiClient.js`:** Specific client for making HTTP requests to the chosen external weather API (e.g., using `axios` or `node-fetch`). Handles API key injection from environment variables (NFR-002, Business Rule 1).
*   **`services/cacheService.js`:** Abstracts Redis interactions for caching weather data.
*   **`config/env.js`:** Manages environment variables for API keys and other configurations.

## Data Architecture

### Frontend (TypeScript Interfaces):
Data models on the frontend will be defined using TypeScript interfaces to ensure strong typing and data consistency, aligning with the `requirements_document.md` Data Requirements section.
```typescript
// src/app/shared/models/location.model.ts
export interface Location {
  name: string;
  country?: string; // Optional, as some APIs might only provide city
  latitude: number;
  longitude: number;
}

// src/app/shared/models/current-weather.model.ts
export interface CurrentWeather {
  location: Location;
  temperature: number;
  unit: 'Celsius' | 'Fahrenheit';
  condition: string;
  description: string;
  icon: string; // URL or icon code
  humidity: number;
  windSpeed: number; // In m/s or mph
  timestamp: number; // Unix timestamp or ISO string
}

// src/app/shared/models/forecast-day.model.ts
export interface ForecastDay {
  location: Location;
  date: string; // ISO date string, e.g., 'YYYY-MM-DD'
  tempHigh: number;
  tempLow: number;
  unit: 'Celsius' | 'Fahrenheit';
  condition: string;
  description: string;
  icon: string; // URL or icon code
}
```

### Backend (Data Transformation & Caching):
*   The backend proxy will receive raw data from the external weather API and transform it into the `CurrentWeather` and `ForecastDay` models defined above before sending it to the frontend.
*   **Caching Database (Redis):** Redis will be used as an in-memory data store for caching weather data (NFR-005, Business Rule 3). Cache keys will be constructed based on location (city, latitude/longitude) and unit, with a configurable time-to-live (TTL) to ensure data freshness while reducing external API calls. For example, a key could be `weather:london:celsius:current` or `weather:london:fahrenheit:forecast`.

## API Design - Backend Proxy Endpoints

The backend proxy will expose RESTful API endpoints, allowing the frontend to fetch weather data. All responses will be in JSON format.

*   **Base URL:** `/api`
*   **Endpoints (FR-008):**
    *   `GET /api/current-weather?location={city}[&lat={latitude}&lon={longitude}][&units={metric|imperial}]`
        *   **Description:** Retrieves current weather conditions for a specified location (city name or geographic coordinates).
        *   **Parameters:**
            *   `location`: (Required if `lat` and `lon` are not provided) City name (e.g., `London`).
            *   `lat`: (Optional, with `lon`) Latitude for geolocation search.
            *   `lon`: (Optional, with `lat`) Longitude for geolocation search.
            *   `units`: (Optional) `metric` (Celsius, m/s) or `imperial` (Fahrenheit, miles/hour). Defaults to `metric`.
        *   **Response (200 OK):** `CurrentWeather` object.
        *   **Error Responses:** 400 Bad Request (invalid parameters), 404 Not Found (location not found), 500 Internal Server Error (external API issue).

    *   `GET /api/forecast?location={city}[&lat={latitude}&lon={longitude}][&units={metric|imperial}]`
        *   **Description:** Retrieves a multi-day weather forecast for a specified location.
        *   **Parameters:** Same as `/api/current-weather`.
        *   **Response (200 OK):** An array of `ForecastDay` objects.
        *   **Error Responses:** Same as `/api/current-weather`.

## Security Architecture

*   **API Key Management (NFR-002, Business Rule 1):** External weather API keys will be stored as environment variables on the backend server and never committed to version control or exposed to the client-side. The backend proxy will inject these keys into its requests to the external API.
*   **HTTPS (NFR-002):** All communication between the Angular frontend and the Node.js/Express.js backend proxy, and ideally between the proxy and the external weather API (if supported), will use HTTPS/SSL to ensure data encryption in transit.
*   **Input Validation (Business Rule 4, NFR-002):** Both frontend and backend will perform input validation on user-provided location data to prevent injection attacks or invalid requests. The backend proxy will sanitize and validate all parameters before forwarding them to the external weather API.
*   **CORS Configuration:** The Express.js backend will be configured with appropriate Cross-Origin Resource Sharing (CORS) headers to allow requests only from the Angular frontend's domain, preventing unauthorized cross-origin requests.
*   **Error Handling:** The backend will avoid exposing sensitive internal error details to the client. Generic, user-friendly error messages will be returned instead (FR-007).

## Scalability Considerations

*   **Frontend Scalability:** Angular's default build optimizations (tree-shaking, minification, lazy loading of feature modules) ensure efficient client-side performance. The modular architecture facilitates independent development and scaling of features.
*   **Backend Scalability (NFR-005):**
    *   **Containerization (Docker):** The Express.js backend service will be containerized using Docker, allowing for easy deployment and orchestration in cloud environments (e.g., Kubernetes, AWS Fargate, Azure Container Instances).
    *   **Horizontal Scaling:** The stateless nature of the backend proxy (apart from caching) enables horizontal scaling, where multiple instances can run concurrently behind a load balancer to handle increased request load.
    *   **Caching (Redis):** Implementing Redis caching significantly reduces the load on the external weather API and improves response times, especially for frequently requested locations, thereby enhancing throughput and scalability (NFR-001, NFR-005, Business Rule 3).
    *   **External API Rate Limiting (Business Rule 2):** The backend proxy will implement mechanisms to respect the external weather API's rate limits, potentially queueing or throttling requests to avoid service interruptions.
*   **Reliability (NFR-004):** The backend will incorporate retry mechanisms with exponential backoff for transient failures when communicating with the external weather API. Circuit breakers can be considered for more resilient handling of persistent external API outages.

