#!/bin/bash
# =============================================================================
# Script de Teste — API Unidade Regional (Notícias + Associados)
# =============================================================================
# Pré-requisitos:
#   - Docker rodando: docker compose up -d
#   - Token de API válido gerado no CMS
#   - jq instalado (para parsing JSON)
#
# Uso:
#   ./tests/api/unidade-regional-test.sh SEU_TOKEN_AQUI
#   ou
#   TOKEN=asc_... ./tests/api/unidade-regional-test.sh
# =============================================================================

set -euo pipefail

BASE_URL="${API_URL:-http://localhost:10011}"
TOKEN="${1:-${TOKEN:-}}"
PASS=0
FAIL=0
TOTAL=0

# Cores
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
NC='\033[0m'

# Helpers
assert_status() {
    local expected=$1
    local actual=$2
    local test_name=$3
    TOTAL=$((TOTAL + 1))
    if [ "$expected" = "$actual" ]; then
        echo -e "  ${GREEN}✓ PASS${NC} $test_name (HTTP $actual)"
        PASS=$((PASS + 1))
    else
        echo -e "  ${RED}✗ FAIL${NC} $test_name — esperado HTTP $expected, obtido HTTP $actual"
        FAIL=$((FAIL + 1))
    fi
}

assert_json_field() {
    local json="$1"
    local field="$2"
    local expected="$3"
    local test_name=$4
    TOTAL=$((TOTAL + 1))
    local actual
    actual=$(echo "$json" | jq -r "$field" 2>/dev/null)
    if [ "$expected" = "$actual" ]; then
        echo -e "  ${GREEN}✓ PASS${NC} $test_name (valor: $actual)"
        PASS=$((PASS + 1))
    else
        echo -e "  ${RED}✗ FAIL${NC} $test_name — esperado '$expected', obtido '$actual'"
        FAIL=$((FAIL + 1))
    fi
}

# Validação de entrada
if [ -z "$TOKEN" ]; then
    echo -e "${RED}ERRO: Token não informado.${NC}"
    echo "Uso: $0 SEU_TOKEN_AQUI"
    echo "ou:  TOKEN=asc_... $0"
    exit 1
fi

if ! command -v jq &> /dev/null; then
    echo -e "${YELLOW}AVISO: jq não encontrado. Instale para melhor experiência.${NC}"
    echo "  Ubuntu/Debian: sudo apt install jq"
    echo "  macOS: brew install jq"
fi

echo ""
echo -e "${CYAN}============================================================${NC}"
echo -e "${CYAN} Testes da API — Unidade Regional${NC}"
echo -e "${CYAN} Base URL: $BASE_URL${NC}"
echo -e "${CYAN}============================================================${NC}"
echo ""

# =============================================================================
# 1. AUTENTICAÇÃO — NOTICIAS
# =============================================================================
echo -e "${YELLOW}▸ 1. AUTH — POST /noticias${NC}"

# 1.1 Token válido
HTTP=$(curl -s -o /dev/null -w '%{http_code}' \
    -X POST "$BASE_URL/api/v2/unidaderegional/noticias" \
    -H "Authorization: Bearer $TOKEN" \
    -H "Content-Type: application/json" \
    -d '{"title":"Teste API Curl","content":"Conteúdo automático."}')
assert_status 201 "$HTTP" "POST /noticias com token válido → 201"

# 1.2 Sem token
HTTP=$(curl -s -o /dev/null -w '%{http_code}' \
    -X POST "$BASE_URL/api/v2/unidaderegional/noticias" \
    -H "Content-Type: application/json" \
    -d '{"title":"Sem Token","content":"Conteúdo."}')
assert_status 401 "$HTTP" "POST /noticias sem token → 401"

# 1.3 Token inválido
HTTP=$(curl -s -o /dev/null -w '%{http_code}' \
    -X POST "$BASE_URL/api/v2/unidaderegional/noticias" \
    -H "Authorization: Bearer invalid_token_xyz" \
    -H "Content-Type: application/json" \
    -d '{"title":"Token Errado","content":"Conteúdo."}')
assert_status 401 "$HTTP" "POST /noticias com token inválido → 401"

# 1.4 Sem título (validação)
HTTP=$(curl -s -o /dev/null -w '%{http_code}' \
    -X POST "$BASE_URL/api/v2/unidaderegional/noticias" \
    -H "Authorization: Bearer $TOKEN" \
    -H "Content-Type: application/json" \
    -d '{"content":"Conteúdo sem título."}')
assert_status 422 "$HTTP" "POST /noticias sem título → 422"

echo ""

# =============================================================================
# 2. AUTENTICAÇÃO — ASSOCIADOS
# =============================================================================
echo -e "${YELLOW}▸ 2. AUTH — POST /associados${NC}"

# 2.1 Sem token
HTTP=$(curl -s -o /dev/null -w '%{http_code}' \
    -X POST "$BASE_URL/api/v2/unidaderegional/associados" \
    -H "Content-Type: application/json" \
    -d '{"name":"Associado Teste"}')
assert_status 401 "$HTTP" "POST /associados sem token → 401"

echo ""

# =============================================================================
# 3. LISTAGEM — GET /associados (REQUER AUTH)
# =============================================================================
echo -e "${YELLOW}▸ 3. LIST — GET /associados${NC}"

# 3.1 Com token válido
RESPONSE=$(curl -s -w "\n%{http_code}" \
    -X GET "$BASE_URL/api/v2/unidaderegional/associados" \
    -H "Authorization: Bearer $TOKEN")
HTTP=$(echo "$RESPONSE" | tail -1)
BODY=$(echo "$RESPONSE" | sed '$d')
assert_status 200 "$HTTP" "GET /associados com token válido → 200"

# 3.2 Sem token (agora exige auth)
HTTP=$(curl -s -o /dev/null -w '%{http_code}' \
    -X GET "$BASE_URL/api/v2/unidaderegional/associados")
assert_status 401 "$HTTP" "GET /associados sem token → 401 (protegido)"

# 3.3 Query param ignora sem token (vazia)
HTTP=$(curl -s -o /dev/null -w '%{http_code}' \
    -X GET "$BASE_URL/api/v2/unidaderegional/associados?unidade_regional_id=any-id")
assert_status 401 "$HTTP" "GET /associados?unidade_regional_id=X sem token → 401 (data leak fix)"

echo ""

# =============================================================================
# 4. LISTAGEM — GET /noticias (REQUER AUTH)
# =============================================================================
echo -e "${YELLOW}▸ 4. LIST — GET /noticias${NC}"

# 4.1 Com token válido
RESPONSE=$(curl -s -w "\n%{http_code}" \
    -X GET "$BASE_URL/api/v2/unidaderegional/noticias" \
    -H "Authorization: Bearer $TOKEN")
HTTP=$(echo "$RESPONSE" | tail -1)
BODY=$(echo "$RESPONSE" | sed '$d')
assert_status 200 "$HTTP" "GET /noticias com token válido → 200"

# 4.2 Sem token
HTTP=$(curl -s -o /dev/null -w '%{http_code}' \
    -X GET "$BASE_URL/api/v2/unidaderegional/noticias")
assert_status 401 "$HTTP" "GET /noticias sem token → 401"

# 4.3 Verificar estrutura da resposta
if command -v jq &> /dev/null; then
    RESPONSE=$(curl -s \
        -X GET "$BASE_URL/api/v2/unidaderegional/noticias" \
        -H "Authorization: Bearer $TOKEN")
    assert_json_field "$RESPONSE" ".ok" "true" "GET /noticias → ok:true"
    assert_json_field "$RESPONSE" ".data.unidade_regional_id" "" "GET /noticias → unidade_regional_id presente"
fi

echo ""

# =============================================================================
# 5. CICLO COMPLETO — Criar Associado + Listar + Atualizar
# =============================================================================
echo -e "${YELLOW}▸ 5. CYCLE — Criar → Listar → Atualizar Associado${NC}"

# 5.1 Criar associado novo com description em Markdown
RESPONSE=$(curl -s -w "\n%{http_code}" \
    -X POST "$BASE_URL/api/v2/unidaderegional/associados" \
    -H "Authorization: Bearer $TOKEN" \
    -H "Content-Type: application/json" \
    -d '{"name":"Associado Curl Teste","description":"## Sobre\n\nConvênio com **desconto** de 15%.","tags":"curl-teste","status":"active"}')
HTTP=$(echo "$RESPONSE" | tail -1)
BODY=$(echo "$RESPONSE" | sed '$d')
assert_status 201 "$HTTP" "POST /associados criar novo → 201"

EMPRESA_ID=""
if command -v jq &> /dev/null; then
    EMPRESA_ID=$(echo "$BODY" | jq -r '.data.results[0].empresa_id // empty')
    if [ -n "$EMPRESA_ID" ]; then
        echo -e "  ${CYAN}→ Associado criado: $EMPRESA_ID${NC}"
    fi
fi

# 5.2 Listar associados (deve incluir o criado)
RESPONSE=$(curl -s -w "\n%{http_code}" \
    -X GET "$BASE_URL/api/v2/unidaderegional/associados" \
    -H "Authorization: Bearer $TOKEN")
HTTP=$(echo "$RESPONSE" | tail -1)
BODY=$(echo "$RESPONSE" | sed '$d')
assert_status 200 "$HTTP" "GET /associados listar após criar → 200"

if command -v jq &> /dev/null; then
    TOTAL_COUNT=$(echo "$BODY" | jq -r '.data.total // 0')
    if [ "$TOTAL_COUNT" -gt 0 ] 2>/dev/null; then
        echo -e "  ${GREEN}✓ PASS${NC} GET /associados retorna $TOTAL_COUNT associados"
        PASS=$((PASS + 1))
    else
        echo -e "  ${RED}✗ FAIL${NC} GET /associados retorna 0 associados"
        FAIL=$((FAIL + 1))
    fi
    TOTAL=$((TOTAL + 1))
fi

# 5.3 Atualizar associado (POST com id)
if [ -n "$EMPRESA_ID" ]; then
    RESPONSE=$(curl -s -w "\n%{http_code}" \
        -X POST "$BASE_URL/api/v2/unidaderegional/associados" \
        -H "Authorization: Bearer $TOKEN" \
        -H "Content-Type: application/json" \
        -d "{\"id\":\"$EMPRESA_ID\",\"name\":\"Associado Atualizado Curl\",\"description\":\"## Atualizado\\n\\nNova descrição via API.\"}")
    HTTP=$(echo "$RESPONSE" | tail -1)
    assert_status 200 "$HTTP" "POST /associados atualizar com id → 200"
fi

echo ""

# =============================================================================
# 6. CICLO COMPLETO — Criar Notícia + Atualizar
# =============================================================================
echo -e "${YELLOW}▸ 6. CYCLE — Criar → Listar → Atualizar Notícia${NC}"

# 6.1 Criar notícia
RESPONSE=$(curl -s -w "\n%{http_code}" \
    -X POST "$BASE_URL/api/v2/unidaderegional/noticias" \
    -H "Authorization: Bearer $TOKEN" \
    -H "Content-Type: application/json" \
    -d '{"title":"Notícia Curl Teste","content":"## Título\n\nConteúdo automático com curl."}')
HTTP=$(echo "$RESPONSE" | tail -1)
BODY=$(echo "$RESPONSE" | sed '$d')
assert_status 201 "$HTTP" "POST /noticias criar nova → 201"

NOTICIA_ID=""
if command -v jq &> /dev/null; then
    NOTICIA_ID=$(echo "$BODY" | jq -r '.data.id // empty')
    if [ -n "$NOTICIA_ID" ]; then
        echo -e "  ${CYAN}→ Notícia criada: $NOTICIA_ID${NC}"
    fi
fi

# 6.2 Atualizar notícia (POST com id)
if [ -n "$NOTICIA_ID" ]; then
    RESPONSE=$(curl -s -w "\n%{http_code}" \
        -X POST "$BASE_URL/api/v2/unidaderegional/noticias" \
        -H "Authorization: Bearer $TOKEN" \
        -H "Content-Type: application/json" \
        -d "{\"id\":\"$NOTICIA_ID\",\"title\":\"Notícia Curl Atualizada\",\"subtitle\":\"Subtítulo atualizado\"}")
    HTTP=$(echo "$RESPONSE" | tail -1)
    assert_status 200 "$HTTP" "POST /noticias atualizar com id → 200"

    # 6.3 Listar notícias (deve mostrar a atualizada)
    RESPONSE=$(curl -s -w "\n%{http_code}" \
        -X GET "$BASE_URL/api/v2/unidaderegional/noticias" \
        -H "Authorization: Bearer $TOKEN")
    HTTP=$(echo "$RESPONSE" | tail -1)
    assert_status 200 "$HTTP" "GET /noticias listar após atualizar → 200"
fi

echo ""

# =============================================================================
# 7. ARQUIVAMENTO — DELETE /noticias e /associados
# =============================================================================
echo -e "${YELLOW}▸ 7. ARCHIVE — DELETE /noticias e DELETE /associados${NC}"

# 7.1 Criar notícia para arquivar
RESPONSE=$(curl -s -w "\n%{http_code}" \
    -X POST "$BASE_URL/api/v2/unidaderegional/noticias" \
    -H "Authorization: Bearer $TOKEN" \
    -H "Content-Type: application/json" \
    -d '{"title":"Notícia Para Arquivar","content":"Conteúdo que será arquivado."}')
HTTP=$(echo "$RESPONSE" | tail -1)
BODY=$(echo "$RESPONSE" | sed '$d')

NOTICIA_ARCHIVE_ID=""
if command -v jq &> /dev/null; then
    NOTICIA_ARCHIVE_ID=$(echo "$BODY" | jq -r '.data.id // empty')
fi

if [ -n "$NOTICIA_ARCHIVE_ID" ]; then
    # Arquivar notícia
    HTTP=$(curl -s -o /dev/null -w '%{http_code}' \
        -X DELETE "$BASE_URL/api/v2/unidaderegional/noticias/$NOTICIA_ARCHIVE_ID" \
        -H "Authorization: Bearer $TOKEN")
    assert_status 200 "$HTTP" "DELETE /noticias/{id} arquivar → 200"

    # Tentar atualizar notícia arquivada → 409
    RESPONSE=$(curl -s -w "\n%{http_code}" \
        -X POST "$BASE_URL/api/v2/unidaderegional/noticias" \
        -H "Authorization: Bearer $TOKEN" \
        -H "Content-Type: application/json" \
        -d "{\"id\":\"$NOTICIA_ARCHIVE_ID\",\"title\":\"Tentando Reativar\"}")
    HTTP=$(echo "$RESPONSE" | tail -1)
    assert_status 409 "$HTTP" "POST /noticias com id arquivado → 409 (não reativar)"
fi

echo ""

# =============================================================================
# 8. SEGURANÇA — Rotas sem auth
# =============================================================================
echo -e "${YELLOW}▸ 8. SECURITY — DELETE sem auth${NC}"

# 8.1 DELETE /noticias sem token
HTTP=$(curl -s -o /dev/null -w '%{http_code}' \
    -X DELETE "$BASE_URL/api/v2/unidaderegional/noticias/any-id")
assert_status 401 "$HTTP" "DELETE /noticias sem token → 401"

# 8.2 DELETE /associados sem token
HTTP=$(curl -s -o /dev/null -w '%{http_code}' \
    -X DELETE "$BASE_URL/api/v2/unidaderegional/associados/any-id")
assert_status 401 "$HTTP" "DELETE /associados sem token → 401"

echo ""

# =============================================================================
# RESUMO
# =============================================================================
echo -e "${CYAN}============================================================${NC}"
echo -e "${CYAN} Resultado${NC}"
echo -e "${CYAN}============================================================${NC}"
echo -e " Total:  $TOTAL"
echo -e " ${GREEN}Pass:   $PASS${NC}"
echo -e " ${RED}Fail:   $FAIL${NC}"
echo ""

if [ $FAIL -eq 0 ]; then
    echo -e "${GREEN}✓ TODOS OS TESTES PASSARAM!${NC}"
    exit 0
else
    echo -e "${RED}✗ $FAIL TESTE(S) FALHARAM${NC}"
    exit 1
fi
