#!/bin/bash
# scripts/check-api-endpoints.sh - Проверка всех API эндпоинтов

set -e

echo "🌐 Проверка API эндпоинтов..."
echo "============================="

# Функция для тестирования эндпоинта
test_endpoint() {
    local url="$1"
    local expected_codes="$2"
    local description="$3"
    
    echo -n "🔗 $description: "
    
    local response_code
    response_code=$(curl -s -o /dev/null -w "%{http_code}" "$url" 2>/dev/null || echo "000")
    
    if echo "$expected_codes" | grep -q "$response_code"; then
        echo "✅ ($response_code)"
        return 0
    else
        echo "❌ ($response_code)"
        return 1
    fi
}

echo ""
echo "📡 1. Прямые подключения к контейнерам:"

# Backend endpoints
test_endpoint "http://localhost:8000/admin/" "200 302" "Django Admin"
test_endpoint "http://localhost:8000/api/" "200 404" "Django API Root"
test_endpoint "http://localhost:8000/api/auth/register/" "405" "Register API"
test_endpoint "http://localhost:8000/static/" "404" "Static Files"

# Frontend endpoint
test_endpoint "http://localhost:3000/" "200" "Frontend Home"

echo ""
echo "📡 2. Через nginx (внешние подключения):"

# Through nginx
test_endpoint "http://localhost/admin/" "200 302" "Admin через nginx"
test_endpoint "http://localhost/api/" "200 404" "API через nginx"
test_endpoint "http://localhost/" "200" "Frontend через nginx"

echo ""
echo "📡 3. HTTPS эндпоинты (если SSL настроен):"

# HTTPS endpoints
test_endpoint "https://localhost/admin/" "200 302" "Admin HTTPS" || true
test_endpoint "https://localhost/api/" "200 404" "API HTTPS" || true
test_endpoint "https://localhost/" "200" "Frontend HTTPS" || true

# С доменным именем
test_endpoint "https://links.shareon.kr/admin/" "200 302" "Admin на домене" || true
test_endpoint "https://links.shareon.kr/api/" "200 404" "API на домене" || true
test_endpoint "https://links.shareon.kr/" "200" "Frontend на домене" || true

echo ""
echo "📡 4. Детальная проверка API:"

echo -n "🔗 API Schema (Swagger): "
swagger_code=$(curl -s -o /dev/null -w "%{http_code}" "http://localhost:8000/api/schema/" 2>/dev/null || echo "000")
if [ "$swagger_code" = "200" ]; then
    echo "✅ ($swagger_code)"
else
    echo "❌ ($swagger_code)"
fi

echo -n "🔗 API Documentation: "
docs_code=$(curl -s -o /dev/null -w "%{http_code}" "http://localhost:8000/api/docs/" 2>/dev/null || echo "000")
if [ "$docs_code" = "200" ]; then
    echo "✅ ($docs_code)"
else
    echo "❌ ($docs_code)"
fi

echo ""
echo "📡 5. Проверка специфических API эндпоинтов:"

# Проверяем конкретные API endpoints
echo -n "🔗 Auth endpoints: "
if curl -s -X POST -H "Content-Type: application/json" \
   -d '{"username":"test","password":"test","email":"test@test.com"}' \
   http://localhost:8000/api/auth/register/ 2>/dev/null | grep -q -E "(error|success|created|username|email)" 2>/dev/null; then
    echo "✅ (отвечает)"
else
    echo "❌ (не отвечает)"
fi

echo ""
echo "🏁 Проверка эндпоинтов завершена!"