#!/bin/bash

echo "🔐 Testing Emergency Service Authorization Documentation"
echo "=" $(printf "%0.s=" {1..60})

# Проверяем что эндпоинт требует авторизацию
echo "🚫 Testing unauthorized access..."
UNAUTHORIZED_RESPONSE=$(curl -s -X GET "http://localhost:8002/api/v1/stats")
echo "Response without token: $UNAUTHORIZED_RESPONSE"

if echo "$UNAUTHORIZED_RESPONSE" | grep -q "Not authenticated"; then
    echo "✅ Correctly requires authentication"
else
    echo "❌ Should require authentication but doesn't"
fi

echo ""

# Получаем токен и тестируем авторизованный доступ
echo "🔑 Testing authorized access..."
TOKEN=$(curl -s -X POST "http://localhost:8001/api/v1/auth/login" \
  -H "Content-Type: application/json" \
  -d '{"username": "testuser", "password": "testpass"}' | \
  jq -r '.access_token')

if [ "$TOKEN" = "null" ] || [ -z "$TOKEN" ]; then
    echo "❌ Failed to get authentication token"
    exit 1
fi

echo "✅ Authentication token obtained: ${TOKEN:0:20}..."

# Тестируем авторизованный запрос
AUTHORIZED_RESPONSE=$(curl -s -X GET "http://localhost:8002/api/v1/stats" \
  -H "Authorization: Bearer $TOKEN")

echo "Response with token:"
echo "$AUTHORIZED_RESPONSE" | jq '.'

if echo "$AUTHORIZED_RESPONSE" | grep -q "total_alerts"; then
    echo "✅ Authorized access works correctly"
else
    echo "❌ Authorized access failed"
fi

echo ""

# Проверяем OpenAPI схему
echo "📋 Checking OpenAPI security scheme..."
SECURITY_SCHEME=$(curl -s "http://localhost:8002/openapi.json" | jq '.components.securitySchemes')
echo "Security schemes:"
echo "$SECURITY_SCHEME" | jq '.'

if echo "$SECURITY_SCHEME" | grep -q "JWT Bearer Token"; then
    echo "✅ JWT Bearer Token scheme is properly configured"
else
    echo "❌ JWT Bearer Token scheme is missing"
fi

# Проверяем что эндпоинты требуют авторизацию в схеме
STATS_SECURITY=$(curl -s "http://localhost:8002/openapi.json" | jq '.paths."/api/v1/stats".get.security')
echo ""
echo "Stats endpoint security requirements:"
echo "$STATS_SECURITY" | jq '.'

if echo "$STATS_SECURITY" | grep -q "JWT Bearer Token"; then
    echo "✅ Stats endpoint correctly shows JWT Bearer Token requirement"
else
    echo "❌ Stats endpoint missing JWT Bearer Token requirement in schema"
fi

echo ""
echo "=" $(printf "%0.s=" {1..60})
echo "🎯 Authorization documentation test completed!"
echo ""
echo "📚 Documentation available at:"
echo "   - Swagger UI: http://localhost:8002/docs"
echo "   - ReDoc: http://localhost:8002/redoc"
echo "   - OpenAPI JSON: http://localhost:8002/openapi.json"