# 🧪 Testing Guide - Backend API

## ✅ Verificações Antes de Começar

```bash
# 1. Verificar Docker
docker --version
docker-compose --version

# 2. Verificar Go (opcional, para desenvolvimento local)
go version

# 3. Verificar espaço em disco
df -h  # macOS/Linux
dir C:\  # Windows

# 4. Verificar portas livres
# Necessárias: 80, 443 (Traefik), 8080 (Backend), 5432 (DB), 6379 (Redis), 9000 (MinIO)
```

---

## 🚀 Inicialização do Stack

### Passo 1: Setup Inicial

```bash
cd g:\Projetos\aggios-app

# Copiar .env
cp .env.example .env

# Ajustar valores se necessário
# nano .env ou code .env
```

### Passo 2: Iniciar Containers

```bash
# Windows
.\scripts\start-dev.bat

# Linux/macOS
./scripts/start-dev.sh

# Ou manual
docker-compose up -d
```

### Passo 3: Verificar Status

```bash
# Listar containers
docker-compose ps

# Esperado:
# NAME              STATUS
# traefik           Up (healthy)
# postgres          Up (healthy)
# redis             Up (healthy)
# minio             Up (healthy)
# backend           Up (healthy)
```

### Passo 4: Ver Logs (se houver erro)

```bash
# Ver logs do backend
docker-compose logs -f backend

# Ver logs do postgres
docker-compose logs -f postgres

# Ver todos os logs
docker-compose logs -f
```

---

## 🧪 Testes de Endpoints

### Health Check (SEM autenticação)

```bash
curl -X GET http://localhost:8080/api/health

# Resposta esperada:
{
  "status": "up",
  "timestamp": 1733376000,
  "database": true,
  "redis": true,
  "minio": true
}
```

**Status esperado**: 200 OK ✅

---

### Teste com Postman/Insomnia

#### 1. Health Check (GET)
```
URL: http://localhost:8080/api/health
Method: GET
Auth: None
Expected: 200 OK
```

#### 2. Login (POST)
```
URL: http://localhost:8080/api/auth/login
Method: POST
Headers:
  Content-Type: application/json

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

Expected: 200 OK (com tokens)
```

#### 3. Get Profile (GET com JWT)
```
URL: http://localhost:8080/api/users/me
Method: GET
Auth: Bearer Token
Headers:
  Authorization: Bearer {access_token}

Expected: 200 OK ou 401 Unauthorized (token inválido)
```

---

## 🧬 Testes com cURL

### 1. Health Check

```bash
curl -i -X GET http://localhost:8080/api/health
```

**Resposta esperada**:
```
HTTP/1.1 200 OK
Content-Type: application/json
{
  "status": "up",
  "timestamp": 1733376000,
  "database": true
}
```

### 2. Login (vai falhar pois não temos implementação)

```bash
curl -i -X POST http://localhost:8080/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "test@example.com",
    "password": "Test123!@#"
  }'
```

**Resposta esperada**:
```
HTTP/1.1 200 OK ou 400 Bad Request (conforme implementação)
```

### 3. Testar CORS

```bash
curl -i -X OPTIONS http://localhost:8080/api/health \
  -H "Origin: http://localhost:3000" \
  -H "Access-Control-Request-Method: GET"
```

**Headers esperados**:
```
Access-Control-Allow-Origin: http://localhost:3000
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS, PATCH
```

---

## 🗄️ Testes de Database

### Verificar PostgreSQL

```bash
# Conectar ao container
docker-compose exec postgres psql -U aggios -d aggios_db

# SQL queries:
\dt                                    # listar tables
SELECT * FROM tenants;                 # listar tenants
SELECT * FROM users;                   # listar users (vazio inicialmente)
SELECT * FROM refresh_tokens;          # listar tokens
\q                                     # sair
```

### Inserir Tenant de Teste

```bash
docker-compose exec postgres psql -U aggios -d aggios_db -c "
INSERT INTO tenants (name, domain, subdomain, is_active) 
VALUES ('Test Tenant', 'test.aggios.app', 'test', true)
ON CONFLICT DO NOTHING;
"
```

---

## 💾 Testes de Cache (Redis)

```bash
# Conectar ao Redis
docker-compose exec redis redis-cli -a changeme

# Comandos básicos:
PING                   # verificar conexão
SET testkey "value"    # set key
GET testkey            # get value
DEL testkey            # delete key
DBSIZE                 # número de keys
FLUSHDB                # limpar database
quit                   # sair
```

---

## 🗂️ Testes de Storage (MinIO)

### Via Browser

1. Abrir: http://minio-console.localhost
2. Login:
   - Usuário: `minioadmin`
   - Senha: `changeme` (ou conforme .env)
3. Explorar buckets (deve existir: `aggios`)

### Via Command Line

```bash
# Acessar MinIO dentro do container
docker-compose exec minio mc ls minio

# Criar bucket de teste
docker-compose exec minio mc mb minio/test-bucket

# Listar buckets
docker-compose exec minio mc ls minio
```

---

## 📡 Testes de Traefik

### Dashboard Traefik

```
URL: http://traefik.localhost
Auth: admin / admin (default)
```

Aqui você pode ver:
- ✅ Routes configuradas
- ✅ Middlewares ativas
- ✅ Services
- ✅ Certificados SSL
- ✅ Health dos endpoints

---

## 🧪 Testes de Performance

### Load Testing com Apache Bench

```bash
# 1000 requisições, 10 concorrentes
ab -n 1000 -c 10 http://localhost:8080/api/health

# Esperado:
# - Requests per second: > 100
# - Failed requests: 0
# - Total time: < 10s
```

### Load Testing com wrk

```bash
# Instalar: https://github.com/wg/wrk
wrk -t4 -c100 -d30s http://localhost:8080/api/health

# Esperado:
# Requests/sec: > 500
# Latency avg: < 100ms
```

---

## 🔍 Debugging

### 1. Ver Logs em Tempo Real

```bash
# Backend
docker-compose logs -f backend

# Postgres
docker-compose logs -f postgres

# Redis
docker-compose logs -f redis

# Traefik
docker-compose logs -f traefik
```

### 2. Entrar em Container

```bash
# Backend
docker-compose exec backend /bin/sh

# Postgres
docker-compose exec postgres /bin/bash

# Redis
docker-compose exec redis /bin/sh
```

### 3. Network Debugging

```bash
# Verificar network
docker-compose exec backend ping postgres   # Test DB
docker-compose exec backend ping redis      # Test Cache
docker-compose exec backend ping minio      # Test Storage
```

---

## ✅ Checklist de Validação

### Infrastructure
- [ ] Docker running: `docker --version`
- [ ] docker-compose up: `docker-compose ps` (all UP)
- [ ] All 6 services healthy (postgres, redis, minio, backend, etc)
- [ ] Traefik dashboard acessível
- [ ] MinIO console acessível

### Backend
- [ ] Health endpoint respond: `/api/health` → 200 OK
- [ ] CORS headers corretos
- [ ] JWT middleware carregado
- [ ] Database conexão OK
- [ ] Redis conexão OK
- [ ] MinIO conexão OK

### Database
- [ ] PostgreSQL running
- [ ] Database `aggios_db` existe
- [ ] Tables criadas (users, tenants, refresh_tokens)
- [ ] Indexes criados
- [ ] Can SELECT * FROM tables

### Cache
- [ ] Redis running
- [ ] Redis password funciona
- [ ] PING retorna PONG
- [ ] SET/GET funciona

### Storage
- [ ] MinIO running
- [ ] Console acessível
- [ ] Bucket `aggios` criado
- [ ] Can upload/download files

### API
- [ ] `/api/health` → 200 OK
- [ ] CORS headers presentes
- [ ] Error responses corretas
- [ ] Security headers presentes

---

## 🆘 Troubleshooting

### Backend não conecta em PostgreSQL

```bash
# 1. Verificar se postgres está running
docker-compose logs postgres

# 2. Testar conexão
docker-compose exec postgres pg_isready -U aggios

# 3. Reset database
docker-compose down postgres
docker-compose up -d postgres
docker-compose logs -f postgres

# 4. Esperar ~10s e tentar novamente
```

### Redis não conecta

```bash
# 1. Verificar se está running
docker-compose logs redis

# 2. Testar PING
docker-compose exec redis redis-cli -a changeme ping

# 3. Verificar password em .env
grep REDIS_PASSWORD .env

# 4. Reset
docker-compose restart redis
```

### MinIO não inicia

```bash
# 1. Ver logs
docker-compose logs minio

# 2. Verificar espaço em disco
df -h

# 3. Resetar volume
docker-compose down -v minio
docker-compose up -d minio
```

### Traefik não resolve domínios

```bash
# 1. Editar /etc/hosts (Linux/macOS)
# 127.0.0.1 traefik.localhost
# 127.0.0.1 minio.localhost
# 127.0.0.1 minio-console.localhost

# 2. Windows: C:\Windows\System32\drivers\etc\hosts
# 127.0.0.1 traefik.localhost
# 127.0.0.1 minio.localhost
```

---

## 📊 Métricas Esperadas

### Latência
```
GET /api/health: < 50ms
POST /api/auth/login: 100-200ms (incluindo hash)
SELECT simples: 5-10ms
```

### Throughput
```
Health endpoint: > 1000 req/s
Login endpoint: > 100 req/s
```

### Resource Usage
```
Backend: ~50MB RAM
PostgreSQL: ~100MB RAM
Redis: ~20MB RAM
MinIO: ~50MB RAM
Total: ~220MB RAM
```

---

## 🎓 Exemplo: Testar Fluxo Completo

### Cenário: User signup -> login -> access profile

```bash
# 1. Verificar health
curl http://localhost:8080/api/health

# 2. Tentar login (vai falhar - não implementado)
curl -X POST http://localhost:8080/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email":"user@test.com","password":"Test123!@#"}'

# 3. Verificar database
docker-compose exec postgres psql -U aggios -d aggios_db \
  -c "SELECT * FROM users;"

# 4. Verificar cache
docker-compose exec redis redis-cli DBSIZE

# 5. Verificar storage
docker-compose exec minio mc ls minio
```

---

## ✨ Próximas Etapas de Teste

Após implementar a autenticação real:

1. **Unit Tests**
   ```bash
   cd backend
   go test ./...
   go test -v -cover ./...
   ```

2. **Integration Tests**
   ```bash
   go test -tags=integration ./...
   ```

3. **Load Tests**
   ```bash
   ab -n 10000 -c 100 https://api.aggios.app/api/health
   ```

4. **Security Tests**
   - OWASP ZAP
   - Burp Suite
   - SQL injection tests
   - XSS tests

---

## 📞 Checklist Final

- [ ] Stack started (`docker-compose ps`)
- [ ] Health endpoint works (200 OK)
- [ ] Database tables created
- [ ] Redis responding
- [ ] MinIO bucket created
- [ ] Traefik dashboard accessible
- [ ] CORS headers correct
- [ ] Error responses formatted
- [ ] Documentation reviewed
- [ ] Ready for development

---

**Status**: ✅ Ready for Testing  
**Próximo**: Implementar autenticação real em `backend/internal/api/handlers/auth.go`

🧪 **Bora testar!**
