# High-Level Design (HLD)

## 1. Architectural Overview

The system follows **Clean Architecture** principles to ensure separation of concerns, testability, and independence from frameworks. It utilizes **CQRS** (Command Query Responsibility Segregation) via the **MediatR** library to decouple read and write operations, ensuring scalable and maintainable code.

### 1.1. Project Layers

* **Domain**: Contains core business logic, entities, value objects, domain events, and custom exceptions. It has zero dependencies on other layers or external frameworks.
* **Application**: Defines use cases and coordinates business logic. It contains MediatR Commands, Queries, Handlers, and validation rules (FluentValidation).
* **Infrastructure**: Implements interfaces defined in the Application layer, such as Persistence (EF Core), Identity (JWT), Caching (Redis), and third-party API integrations.
* **Presentation (WebAPI / AdminAPI)**: Acts as the entry point for clients, handling HTTP requests, routing, security middlewares, and returning standardized API responses.

## 2. Technology Stack & Infrastructure

* **Framework**: .NET Core (8/9).
* **Persistence**: Entity Framework (EF) Core with SQL Server / PostgreSQL.
* **Caching**: **Redis** for distributed session management, refresh token storage, and performance optimization of frequent queries.
* **Messaging**: MediatR for in-process messaging. Extensible to asynchronous message brokers (RabbitMQ/Kafka) for background tasks and microservice communication.
* **Observability**: **Serilog** for structured logging (sinking to Seq/Elasticsearch) and **OpenTelemetry** for distributed tracing and monitoring.

## 3. Core Technical Strategies

### 3.1. Security & Authentication Architecture

* **Authentication**: Stateless authentication using **JWT** (JSON Web Tokens).
* **Token Rotation**: Implements a secure **Refresh Token** mechanism. Refresh tokens are hashed using a token hasher before being stored in the database to prevent leakage.
* **Single Active Session**: Logging in automatically revokes previous active refresh tokens for the user, forcing a single active session.
* **Authorization**: Role-based access control (RBAC) and policy-based authorization managed through claims-based identity.

### 3.2. Data Management & CQRS

* **Commands**: Handled by MediatR to perform write operations (Create, Update, Delete) and mutate system state. Often wrapped in database transactions via an `IUnitOfWork`.
* **Queries**: Optimized for read-only operations, often bypassing complex domain models to query the database directly (e.g., using EF Core `AsNoTracking` or Dapper) and returning flat **DTOs** (Data Transfer Objects).
* **Validation**: Automated input validation using **FluentValidation** integrated directly into the MediatR pipeline behavior, ensuring invalid requests are rejected before reaching handlers.

### 3.3. Caching Strategy (Redis)

* **Key Convention**: Strictly namespaced keys using the pattern `{app}:{layer}:{entity}:{action}:{identifier}`.
* **Data Types**: Optimized use of `Hash` for objects, `String` for simple data, and `Set` for tracking grouping tags.
* **Invalidation**: Tag-based invalidation ensures that when an entity is updated, all related cached queries are instantly purged.
* **Mandatory TTL**: Every cached item has an explicit Time-To-Live (TTL) to prevent memory leaks and ensure data freshness.

### 3.4. Error Handling & Response Standard

* **Global Exception Handling**: Centralized middleware/exception filter to catch all unhandled exceptions, preventing stack trace leaks and transforming them into a standard JSON format.
* **Result Pattern**: All API responses wrap data in a standardized `ApiResponse<T>` or `Result<T>` object, ensuring consistency in error codes, success markers, and payload structure across the FE/BE bridge.

## 4. Deployment & CI/CD Strategy

* **Containerization**: Multi-stage **Docker** builds for Backend APIs to ensure minimal image sizes and consistent runtime environments.
* **Orchestration**: **Docker Compose** for local development and local testing. Target environments use Kubernetes or managed container services.
* **CI/CD Pipelines**: Automated GitHub Actions / GitLab CI pipelines for restoring over NuGet, building, running unit and integration tests, building Docker images, and deploying to servers.

---

## 5. System Flow Diagram (Context & Container)

```mermaid
graph TD
    Client[Client Apps : Web / Mobile] -->|HTTPS / JWT| API[Presentation : WebAPI / AdminAPI]
  
    subgraph "Clean Architecture Core"
        API -->|MediatR Command/Query| App[Application Layer]
        App -->|Uses Entities & Interfaces| Domain[Domain Layer]
    end
  
    subgraph "Infrastructure Layer"
        App -->|Calls Implementations| Infra[Infrastructure Layer]
        Infra -->|EF Core Queries| DB[(SQL Database)]
        Infra -->|StackExchange.Redis| Redis[(Redis Cache)]
        Infra -->|Serilog| Logs[Logging System]
    end
```
