#!/bin/bash
# scripts/ci/test.sh - Запуск тестов

set -e

echo "🧪 Running CatLink tests..."

# Проверка наличия контейнеров
if ! docker-compose ps | grep -q "Up"; then
    echo "📦 Starting containers for testing..."
    docker-compose up -d
    sleep 30
fi

# Подготовка базы данных для тестов
echo "🗄️ Preparing test database..."
docker-compose exec -T web python manage.py migrate --noinput
docker-compose exec -T web python manage.py collectstatic --noinput

# Создание тестового пользователя
echo "👤 Creating test user..."
docker-compose exec -T web python manage.py shell << 'EOF'
from django.contrib.auth import get_user_model
User = get_user_model()
if not User.objects.filter(username='testuser').exists():
    User.objects.create_user(username='testuser', email='test@example.com', password='testpass123')
    print("Test user created")
else:
    print("Test user already exists")
EOF

# Backend тесты
echo "🔧 Running backend tests..."
echo "  • Django unit tests..."
docker-compose exec -T web python manage.py test --verbosity=2 --keepdb || {
    echo "❌ Backend tests failed"
    docker-compose logs web | tail -50
    exit 1
}

# API тесты
echo "🌐 Running API tests..."
echo "  • Testing API endpoints..."

# Проверка основных API эндпоинтов
api_base="http://localhost:8000/api"

# Тест API root
api_root=$(curl -s -o /dev/null -w "%{http_code}" "$api_base/")
echo "    - API root: $api_root"

# Тест регистрации
echo "    - Testing user registration..."
register_response=$(curl -s -X POST "$api_base/auth/register/" \
    -H "Content-Type: application/json" \
    -d '{
        "username": "testuser2",
        "email": "testuser2@example.com",
        "password": "testpass123",
        "password2": "testpass123"
    }' \
    -w "%{http_code}")

if echo "$register_response" | grep -q "200\|201"; then
    echo "      ✅ Registration test passed"
else
    echo "      ⚠️ Registration test failed: $register_response"
fi

# Тест логина
echo "    - Testing user login..."
login_response=$(curl -s -X POST "$api_base/auth/login/" \
    -H "Content-Type: application/json" \
    -d '{
        "username": "testuser",
        "password": "testpass123"
    }')

if echo "$login_response" | grep -q "access"; then
    echo "      ✅ Login test passed"
    # Извлечение токена для дальнейших тестов
    token=$(echo "$login_response" | grep -o '"access":"[^"]*"' | cut -d'"' -f4)
else
    echo "      ⚠️ Login test failed: $login_response"
    token=""
fi

# Тесты авторизованных эндпоинтов
if [ -n "$token" ]; then
    echo "    - Testing authorized endpoints..."
    
    # Тест создания группы
    group_response=$(curl -s -X POST "$api_base/groups/" \
        -H "Authorization: Bearer $token" \
        -H "Content-Type: application/json" \
        -d '{
            "name": "Test Group",
            "description": "Test group for CI"
        }' \
        -w "%{http_code}")
    
    if echo "$group_response" | grep -q "200\|201"; then
        echo "      ✅ Group creation test passed"
    else
        echo "      ⚠️ Group creation test failed: $group_response"
    fi
    
    # Тест получения групп
    groups_response=$(curl -s -H "Authorization: Bearer $token" "$api_base/groups/" -w "%{http_code}")
    if echo "$groups_response" | grep -q "200"; then
        echo "      ✅ Groups list test passed"
    else
        echo "      ⚠️ Groups list test failed: $groups_response"
    fi
fi

# Frontend тесты
echo "💻 Running frontend tests..."
echo "  • NextJS build test..."
docker-compose exec -T frontend npm run build || {
    echo "❌ Frontend build test failed"
    docker-compose logs frontend | tail -50
    exit 1
}

echo "  • Frontend unit tests..."
docker-compose exec -T frontend npm test -- --passWithNoTests --watchAll=false || {
    echo "⚠️ Frontend unit tests failed or no tests found"
}

# E2E тесты (если доступны)
echo "🌍 Running E2E tests..."
if [ -f "frontend/linktree-frontend/package.json" ] && grep -q "cypress\|playwright" "frontend/linktree-frontend/package.json"; then
    echo "  • Running end-to-end tests..."
    docker-compose exec -T frontend npm run test:e2e || {
        echo "⚠️ E2E tests failed"
    }
else
    echo "  • No E2E tests configured, skipping..."
fi

# Интеграционные тесты
echo "🔗 Running integration tests..."
echo "  • Testing frontend-backend integration..."

# Проверка что фронтенд может загрузиться
frontend_status=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:3000)
echo "    - Frontend accessibility: $frontend_status"

# Проверка что фронтенд может обращаться к API
api_from_frontend=$(docker-compose exec -T frontend sh -c "
    curl -s -o /dev/null -w '%{http_code}' http://web:8000/api/
") || echo "000"
echo "    - API accessibility from frontend: $api_from_frontend"

# Производительные тесты (базовые)
echo "⚡ Running basic performance tests..."
echo "  • API response time test..."
api_time=$(curl -s -o /dev/null -w "%{time_total}" "$api_base/")
echo "    - API response time: ${api_time}s"

if (( $(echo "$api_time < 2.0" | bc -l) )); then
    echo "      ✅ API response time is acceptable"
else
    echo "      ⚠️ API response time is slow"
fi

# Проверка использования памяти
echo "  • Memory usage check..."
docker stats --no-stream --format "table {{.Name}}\t{{.MemUsage}}" | grep -E "(web|frontend)"

# Генерация отчета о тестах
echo "📊 Generating test report..."
mkdir -p /tmp/test-reports

cat > /tmp/test-reports/test-summary.txt << EOF
CatLink Test Summary
==================
Date: $(date)
Commit: ${DRONE_COMMIT_SHA:-"local"}
Branch: ${DRONE_BRANCH:-"local"}

API Tests:
- Root endpoint: $api_root
- Registration: $(echo "$register_response" | grep -q "200\|201" && echo "PASS" || echo "FAIL")
- Login: $([ -n "$token" ] && echo "PASS" || echo "FAIL")
- Groups CRUD: $(echo "$group_response" | grep -q "200\|201" && echo "PASS" || echo "FAIL")

Frontend Tests:
- Build: PASS
- Accessibility: $frontend_status

Integration Tests:
- Frontend-Backend: $([ "$api_from_frontend" = "200" ] && echo "PASS" || echo "FAIL")

Performance:
- API Response Time: ${api_time}s
EOF

echo "✅ All tests completed!"
echo "📁 Test reports saved to /tmp/test-reports/"
cat /tmp/test-reports/test-summary.txt