# API Reference - Aggios Backend

## Base URL

- **Development**: `http://localhost:8080`
- **Production**: `https://api.aggios.app` ou `https://{subdomain}.aggios.app`

## Authentication

Todos os endpoints protegidos requerem header:

```
Authorization: Bearer {access_token}
```

## Endpoints

### 🔐 Autenticação

#### Login
```
POST /api/auth/login
Content-Type: application/json

{
  "email": "user@example.com",
  "password": "Senha123!@#"
}

Response 200:
{
  "access_token": "eyJhbGciOiJIUzI1NiIs...",
  "refresh_token": "aB_c123xYz...",
  "token_type": "Bearer",
  "expires_in": 86400
}
```

#### Register
```
POST /api/auth/register
Content-Type: application/json

{
  "email": "newuser@example.com",
  "password": "Senha123!@#",
  "confirm_password": "Senha123!@#",
  "first_name": "João",
  "last_name": "Silva"
}

Response 201:
{
  "data": {
    "id": "123e4567-e89b-12d3-a456-426614174000",
    "email": "newuser@example.com",
    "first_name": "João",
    "last_name": "Silva",
    "created_at": "2024-12-05T10:00:00Z"
  },
  "message": "Usuário registrado com sucesso",
  "code": 201,
  "timestamp": 1733376000
}
```

#### Refresh Token
```
POST /api/auth/refresh
Content-Type: application/json

{
  "refresh_token": "aB_c123xYz..."
}

Response 200:
{
  "data": {
    "access_token": "eyJhbGciOiJIUzI1NiIs...",
    "token_type": "Bearer",
    "expires_in": 86400
  },
  "message": "Token renovado com sucesso",
  "code": 200,
  "timestamp": 1733376000
}
```

#### Logout
```
POST /api/logout
Authorization: Bearer {access_token}

Response 200:
{
  "data": null,
  "message": "Logout realizado com sucesso",
  "code": 200,
  "timestamp": 1733376000
}
```

### 👤 Usuário

#### Get Profil
```
GET /api/users/me
Authorization: Bearer {access_token}

Response 200:
{
  "data": {
    "id": "123e4567-e89b-12d3-a456-426614174000",
    "email": "user@example.com",
    "first_name": "João",
    "last_name": "Silva",
    "tenant_id": "tenant-123",
    "is_active": true,
    "created_at": "2024-12-05T10:00:00Z",
    "updated_at": "2024-12-05T10:00:00Z"
  },
  "message": "Usuário obtido com sucesso",
  "code": 200,
  "timestamp": 1733376000
}
```

#### Update Perfil
```
PUT /api/users/me
Authorization: Bearer {access_token}
Content-Type: application/json

{
  "first_name": "João",
  "last_name": "Silva",
  "email": "newemail@example.com"
}

Response 200:
{
  "data": {
    "id": "123e4567-e89b-12d3-a456-426614174000",
    "email": "newemail@example.com",
    "first_name": "João",
    "last_name": "Silva",
    "updated_at": "2024-12-05T11:00:00Z"
  },
  "message": "Usuário atualizado com sucesso",
  "code": 200,
  "timestamp": 1733376000
}
```

#### Change Password
```
POST /api/users/me/change-password
Authorization: Bearer {access_token}
Content-Type: application/json

{
  "current_password": "SenhaAtual123!@#",
  "new_password": "NovaSenha456!@#",
  "confirm_password": "NovaSenha456!@#"
}

Response 200:
{
  "data": null,
  "message": "Senha alterada com sucesso",
  "code": 200,
  "timestamp": 1733376000
}
```

### 🏢 Tenant

#### Get Tenant
```
GET /api/tenant
Authorization: Bearer {access_token}

Response 200:
{
  "data": {
    "id": "tenant-123",
    "name": "Acme Corp",
    "domain": "acme.aggios.app",
    "subdomain": "acme",
    "is_active": true,
    "created_at": "2024-12-05T10:00:00Z",
    "updated_at": "2024-12-05T10:00:00Z"
  },
  "message": "Tenant obtido com sucesso",
  "code": 200,
  "timestamp": 1733376000
}
```

#### Update Tenant
```
PUT /api/tenant
Authorization: Bearer {access_token}
Content-Type: application/json

{
  "name": "Acme Corporation",
  "domain": "acmecorp.aggios.app"
}

Response 200:
{
  "data": {
    "id": "tenant-123",
    "name": "Acme Corporation",
    "domain": "acmecorp.aggios.app"
  },
  "message": "Tenant atualizado com sucesso",
  "code": 200,
  "timestamp": 1733376000
}
```

### 📁 Files (MinIO)

#### Upload File
```
POST /api/files/upload
Authorization: Bearer {access_token}
Content-Type: multipart/form-data

Form Data:
- file: (binary)
- folder: "agencias" (opcional)

Response 201:
{
  "data": {
    "id": "file-123",
    "name": "documento.pdf",
    "url": "https://minio.aggios.app/aggios/file-123",
    "size": 1024,
    "mime_type": "application/pdf",
    "created_at": "2024-12-05T10:00:00Z"
  },
  "message": "Arquivo enviado com sucesso",
  "code": 201,
  "timestamp": 1733376000
}
```

#### Delete File
```
DELETE /api/files/{file_id}
Authorization: Bearer {access_token}

Response 200:
{
  "data": null,
  "message": "Arquivo deletado com sucesso",
  "code": 200,
  "timestamp": 1733376000
}
```

### ❤️ Health

#### Health Check
```
GET /api/health

Response 200:
{
  "status": "up",
  "timestamp": 1733376000,
  "checks": {
    "database": true,
    "redis": true,
    "minio": true
  }
}
```

## Error Responses

### 400 Bad Request
```json
{
  "error": "validation_error",
  "message": "Validação falhou",
  "code": 400,
  "timestamp": 1733376000,
  "path": "/api/auth/login",
  "errors": [
    {
      "field": "email",
      "message": "Email inválido"
    }
  ]
}
```

### 401 Unauthorized
```json
{
  "error": "unauthorized",
  "message": "Token expirado ou inválido",
  "code": 401,
  "timestamp": 1733376000,
  "path": "/api/users/me"
}
```

### 403 Forbidden
```json
{
  "error": "forbidden",
  "message": "Acesso negado",
  "code": 403,
  "timestamp": 1733376000,
  "path": "/api/tenant"
}
```

### 404 Not Found
```json
{
  "error": "not_found",
  "message": "Recurso não encontrado",
  "code": 404,
  "timestamp": 1733376000,
  "path": "/api/users/invalid-id"
}
```

### 429 Too Many Requests
```json
{
  "error": "rate_limited",
  "message": "Muitas requisições. Tente novamente mais tarde",
  "code": 429,
  "timestamp": 1733376000,
  "path": "/api/auth/login"
}
```

### 500 Internal Server Error
```json
{
  "error": "internal_server_error",
  "message": "Erro interno do servidor",
  "code": 500,
  "timestamp": 1733376000,
  "path": "/api/users/me",
  "trace_id": "abc123"
}
```

## HTTP Status Codes

| Código | Significado |
|--------|-------------|
| 200 | OK - Requisição bem-sucedida |
| 201 | Created - Recurso criado |
| 204 | No Content - Sucesso sem corpo |
| 400 | Bad Request - Erro na requisição |
| 401 | Unauthorized - Autenticação necessária |
| 403 | Forbidden - Acesso negado |
| 404 | Not Found - Recurso não encontrado |
| 409 | Conflict - Conflito (ex: email duplicado) |
| 422 | Unprocessable Entity - Erro de validação |
| 429 | Too Many Requests - Rate limit |
| 500 | Internal Server Error - Erro do servidor |
| 503 | Service Unavailable - Serviço indisponível |

## Rate Limiting

- **Limite**: 100 requisições por minuto (global)
- **Burst**: até 200 requisições em picos
- **Headers de Resposta**:
  - `X-RateLimit-Limit`: limite total
  - `X-RateLimit-Remaining`: requisições restantes
  - `X-RateLimit-Reset`: timestamp do reset

## CORS

Origens permitidas (configuráveis):
- `http://localhost:3000`
- `http://localhost:3001`
- `https://aggios.app`
- `https://dash.aggios.app`

## Versionamento da API

- **Versão Atual**: v1
- **URL Pattern**: `/api/v1/*`
- Compatibilidade para versões antigas mantidas por 1 ano

## Request/Response Format

Todos os endpoints usam:
- **Content-Type**: `application/json`
- **Accept**: `application/json`
- **Charset**: `utf-8`

Exemplo de request:
```bash
curl -X POST https://api.aggios.app/api/auth/login \
  -H "Content-Type: application/json" \
  -H "Accept: application/json" \
  -d '{"email":"user@example.com","password":"Senha123!@#"}'
```

## Documentação Interativa

Swagger/OpenAPI (quando implementado):
```
https://api.aggios.app/docs
```

## WebSocket (Futuro)

Suporte para:
- Real-time notifications
- Live chat/messaging
- Activity streaming

Endpoint: `wss://api.aggios.app/ws`

---

**Última atualização**: Dezembro 2025
**Versão da API**: 1.0.0
