# Arquitetura Completa - Aggios

## 🏗️ Diagrama de Arquitetura

```
┌─────────────────────────────────────────────────────────────────┐
│                     INTERNET / CLIENTES                          │
│  (Web Browsers, Mobile Apps, Third-party Integrations)          │
└────────────────────────┬────────────────────────────────────────┘
                         │
                         ▼
        ┌────────────────────────────────────┐
        │      TRAEFIK (Reverse Proxy)       │
        │   - Load Balancing                 │
        │   - SSL/TLS (Let's Encrypt)        │
        │   - Domain Routing                 │
        │   - Rate Limiting                  │
        └────────────────────────────────────┘
                         │
         ┌───────────────┼───────────────┐
         │               │               │
         ▼               ▼               ▼
    ┌────────┐      ┌────────┐      ┌────────┐
    │Frontend│      │Frontend│      │Backend │
    │Inst.   │      │Dash    │      │API (Go)│
    │(Next)  │      │(Next)  │      │        │
    └────────┘      └────────┘      └────────┘
                                          │
                ┌─────────────────────────┼─────────────────────────┐
                │                         │                         │
                ▼                         ▼                         ▼
         ┌──────────────┐         ┌──────────────┐        ┌──────────────┐
         │  PostgreSQL  │         │    Redis     │        │    MinIO     │
         │   (Banco)    │         │   (Cache)    │        │  (Storage)   │
         │              │         │              │        │              │
         │ - Users      │         │ - Sessions   │        │ - Documentos │
         │ - Tenants    │         │ - Cache      │        │ - Images     │
         │ - Data       │         │ - Rate Limit │        │ - Backups    │
         └──────────────┘         └──────────────┘        └──────────────┘
```

## 🔄 Fluxo de Requisições

### 1. Acesso Web (Navegador)

```
Navegador (usuario.aggios.app)
    ↓
Traefik (DNS: usuario.aggios.app)
    ↓
Frontend Next.js
    ↓ (fetch /api/*)
Traefik
    ↓
Backend API Go
    ↓
PostgreSQL/Redis/MinIO
```

### 2. Acesso Multi-Tenant

```
Cliente de Agência A (acme.aggios.app)
    ↓
Traefik (wildcard *.aggios.app)
    ↓
Backend API (extrai tenant_id do JWT)
    ↓
Query com filtro: WHERE tenant_id = 'acme'
    ↓
PostgreSQL (isolamento garantido)
```

### 3. Fluxo de Autenticação

```
1. POST /api/auth/login
   → Validar email/password
   → Gerar JWT com tenant_id
   → Salvar refresh_token em Redis
   
2. Requisição autenticada
   → Bearer {JWT}
   → Middleware valida JWT
   → Extrai user_id, email, tenant_id
   → Passa ao handler
   
3. Acesso a recurso
   → Backend filtra: SELECT * FROM users WHERE tenant_id = ? AND ...
   → Garante isolamento de dados
```

## 📊 Estrutura de Dados (PostgreSQL)

```sql
-- Tenants (Multi-tenant)
tenants
├── id (UUID)
├── name
├── domain
├── subdomain
├── is_active
├── created_at
└── updated_at

-- Usuários (isolados por tenant)
users
├── id (UUID)
├── email (UNIQUE)
├── password_hash
├── first_name
├── last_name
├── tenant_id (FK → tenants)
├── is_active
├── created_at
└── updated_at

-- Refresh Tokens (sessões)
refresh_tokens
├── id (UUID)
├── user_id (FK → users)
├── token_hash
├── expires_at
└── created_at

-- Índices para performance
├── users.email
├── users.tenant_id
├── tenants.domain
├── tenants.subdomain
└── refresh_tokens.expires_at
```

## 🔐 Modelo de Segurança

### JWT Token Structure
```
Header:
{
  "alg": "HS256",
  "typ": "JWT"
}

Payload:
{
  "user_id": "123e4567-e89b-12d3-a456-426614174000",
  "email": "user@example.com",
  "tenant_id": "acme",
  "exp": 1733462400,
  "iat": 1733376000,
  "jti": "unique-token-id"
}

Signature:
HMACSHA256(base64(header) + "." + base64(payload), JWT_SECRET)
```

### Camadas de Segurança

```
1. TRANSPORT (Traefik)
   ├── HTTPS/TLS (Let's Encrypt)
   ├── HSTS Headers
   └── Rate Limiting

2. APPLICATION (Backend)
   ├── JWT Validation
   ├── CORS Checking
   ├── Input Validation
   ├── Password Hashing (Argon2)
   └── SQL Injection Prevention

3. DATABASE (PostgreSQL)
   ├── Prepared Statements
   ├── Row-level Security (RLS)
   ├── Encrypted Passwords
   └── Audit Logging

4. DATA (Storage)
   ├── Tenant Isolation
   ├── Access Control
   ├── Encryption at rest (MinIO)
   └── Versioning
```

## 🌍 Multi-Tenant Architecture

### Routing Pattern
```
Domain Pattern: {subdomain}.aggios.app

Examples:
- api.aggios.app → General API
- acme.aggios.app → Tenant ACME
- empresa1.aggios.app → Tenant Empresa1
- usuario2.aggios.app → Tenant Usuario2

Traefik Rule:
HostRegexp(`{subdomain:[a-z0-9-]+}\.aggios\.app`)
```

### Data Isolation
```
Level 1: Network
├── Traefik routes by subdomain
└── Passes to single backend instance

Level 2: Application
├── JWT contains tenant_id
├── Every query filtered by tenant_id
└── Cross-tenant access impossible

Level 3: Database
├── Indexes on (tenant_id, field)
├── Foreign key constraints
└── Audit trail per tenant

Level 4: Storage
├── MinIO bucket: aggios/{tenant_id}/*
├── Separate namespaces
└── Access control per tenant
```

## 📦 Docker Stack (Compose)

```yaml
Services:
├── Traefik (1 instance)
│   ├── Port: 80, 443
│   ├── Dashboard: :8080
│   └── Provider: Docker
│
├── Backend (1+ instances)
│   ├── Port: 8080
│   ├── Replicas: configurable
│   └── Load balanced by Traefik
│
├── PostgreSQL (1 primary + optional replicas)
│   ├── Port: 5432
│   ├── Persistence: volume
│   └── Health check: enabled
│
├── Redis (1 instance)
│   ├── Port: 6379
│   ├── Persistence: optional (RDB/AOF)
│   └── Password: required
│
├── MinIO (1+ instances)
│   ├── API: 9000
│   ├── Console: 9001
│   ├── Replicas: configurable
│   └── Persistence: volume
│
├── Frontend Institucional (Next.js)
│   └── Port: 3000
│
└── Frontend Dashboard (Next.js)
    └── Port: 3000
```

## 🔄 Scaling Strategy

### Horizontal Scaling

```
Fase 1 (Development)
├── 1x Backend
├── 1x PostgreSQL
├── 1x Redis
└── 1x MinIO

Fase 2 (Small Production)
├── 2x Backend (load balanced)
├── 1x PostgreSQL + 1x Read Replica
├── 1x Redis (ou Redis Cluster)
└── 1x MinIO (ou MinIO Cluster)

Fase 3 (Large Production)
├── 3-5x Backend
├── 1x PostgreSQL (primary) + 2x Replicas
├── Redis Cluster (3+ nodes)
├── MinIO Cluster (4+ nodes)
└── Kubernetes (optional)
```

## 📱 API Clients

### Web (JavaScript/TypeScript)
```javascript
// fetch com JWT
const response = await fetch('/api/users/me', {
  headers: {
    'Authorization': `Bearer ${accessToken}`,
    'Content-Type': 'application/json'
  }
});
```

### Mobile (React Native / Flutter)
```javascript
// Não diferente de web
// Salvar tokens em AsyncStorage/SecureStorage
// Usar interceptors para auto-refresh
```

### Third-party Integration
```bash
# Via API Key ou OAuth2
curl -X GET https://api.aggios.app/api/data \
  -H "Authorization: Bearer {api_key}" \
  -H "X-API-Version: v1"
```

## 🚀 Pipeline de Deploy

```
1. Git Push
   ↓
2. CI/CD (GitHub Actions / GitLab CI)
   ├── Build Backend
   ├── Run Tests
   ├── Build Docker Image
   └── Push to Registry
   ↓
3. Deploy (Docker Compose / Kubernetes)
   ├── Pull Image
   ├── Run Migrations
   ├── Health Check
   └── Traffic Switch
   ↓
4. Monitoring
   ├── Logs (ELK / Datadog)
   ├── Metrics (Prometheus)
   ├── Errors (Sentry)
   └── Alerts
```

## 📈 Monitoring & Observability

```
Logs
├── Traefik Access Logs
├── Backend Application Logs
├── PostgreSQL Slow Queries
└── MinIO Request Logs
    ↓
    ELK / Datadog / CloudWatch

Metrics
├── Request Rate / Latency
├── DB Connection Pool
├── Redis Memory / Ops
├── MinIO Throughput
└── Docker Container Stats
    ↓
    Prometheus / Grafana

Tracing (Distributed)
├── Request ID propagation
├── Service-to-service calls
└── Database queries
    ↓
    Jaeger / OpenTelemetry

Errors
├── Panics
├── Validation Errors
├── DB Errors
└── 5xx Responses
    ↓
    Sentry / Rollbar
```

## 🔧 Manutenção

### Backups
```
PostgreSQL
├── Full backup (diário)
├── Incremental (a cada 6h)
└── WAL archiving

MinIO
├── Bucket replication
├── Cross-region backup
└── Versioning enabled

Redis
├── RDB snapshots (diário)
└── AOF opcional
```

### Updates
```
1. Traefik
   └── In-place upgrade (zero-downtime)

2. Backend
   ├── Blue-green deployment
   ├── Canary releases
   └── Automatic rollback

3. PostgreSQL
   ├── Replica first
   ├── Failover test
   └── Maintenance window

4. Redis
   └── Cluster rebalance (zero-downtime)

5. MinIO
   └── Rolling update
```

---

**Diagrama criado**: Dezembro 2025
**Versão**: 1.0.0
