#!/bin/bash

echo "🔬 Advanced Emergency Service API Testing"
echo "=" $(printf "%0.s=" {1..60})

# Colors
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

# Counters
TOTAL_TESTS=0
PASSED_TESTS=0
FAILED_TESTS=0

# Test function
test_advanced() {
    local description="$1"
    local command="$2"
    local expected_condition="$3"
    
    TOTAL_TESTS=$((TOTAL_TESTS + 1))
    echo -n "🔸 $description... "
    
    result=$(eval "$command")
    
    if eval "$expected_condition"; then
        echo -e "${GREEN}✅ PASS${NC}"
        PASSED_TESTS=$((PASSED_TESTS + 1))
    else
        echo -e "${RED}❌ FAIL${NC}"
        echo "   Result: $result"
        FAILED_TESTS=$((FAILED_TESTS + 1))
    fi
}

# Get token
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 -e "${RED}❌ Failed to get token${NC}"
    exit 1
fi

echo -e "${GREEN}✅ Token obtained${NC}"
echo ""

# Advanced tests
echo -e "${BLUE}🧪 Testing Edge Cases${NC}"

# Test invalid alert ID
test_advanced "Invalid alert ID (999999)" \
    "curl -s -w '%{http_code}' -X GET 'http://localhost:8002/api/v1/emergency/events/999999' -H 'Authorization: Bearer $TOKEN' | tail -c 3" \
    '[ "$result" = "404" ]'

# Test invalid coordinates
test_advanced "Invalid coordinates (out of range)" \
    "curl -s -X POST 'http://localhost:8002/api/v1/emergency/events' -H 'Authorization: Bearer $TOKEN' -H 'Content-Type: application/json' -d '{\"latitude\": 999, \"longitude\": 999, \"alert_type\": \"general\"}' | jq -r '.detail // empty'" \
    '[ ! -z "$result" ]'

# Test malformed JSON
test_advanced "Malformed JSON request" \
    "curl -s -w '%{http_code}' -X POST 'http://localhost:8002/api/v1/emergency/events' -H 'Authorization: Bearer $TOKEN' -H 'Content-Type: application/json' -d '{invalid json}' | tail -c 3" \
    '[ "$result" = "422" ]'

echo ""
echo -e "${BLUE}📊 Testing Data Consistency${NC}"

# Create alert and check data consistency
echo -n "🔸 Creating alert for consistency test... "
create_response=$(curl -s -X POST "http://localhost:8002/api/v1/emergency/events" \
    -H "Authorization: Bearer $TOKEN" \
    -H "Content-Type: application/json" \
    -d '{
        "latitude": 55.7558,
        "longitude": 37.6176,
        "alert_type": "medical",
        "message": "Consistency test alert",
        "address": "Test Address"
    }')

ALERT_ID=$(echo "$create_response" | jq -r '.id')
if [ "$ALERT_ID" != "null" ] && [ ! -z "$ALERT_ID" ]; then
    echo -e "${GREEN}✅ PASS${NC} (ID: $ALERT_ID)"
    PASSED_TESTS=$((PASSED_TESTS + 1))
    
    # Test data consistency
    test_advanced "Alert appears in active alerts list" \
        "curl -s -X GET 'http://localhost:8002/api/v1/alerts/active' -H 'Authorization: Bearer $TOKEN' | jq '.[] | select(.id == $ALERT_ID) | .id'" \
        '[ "$result" = "$ALERT_ID" ]'
    
    test_advanced "Alert appears in my alerts list" \
        "curl -s -X GET 'http://localhost:8002/api/v1/alerts/my' -H 'Authorization: Bearer $TOKEN' | jq '.[] | select(.id == $ALERT_ID) | .id'" \
        '[ "$result" = "$ALERT_ID" ]'
    
    test_advanced "Alert type is preserved correctly" \
        "curl -s -X GET 'http://localhost:8002/api/v1/emergency/events/$ALERT_ID' -H 'Authorization: Bearer $TOKEN' | jq -r '.alert_type'" \
        '[ "$result" = "medical" ]'
    
else
    echo -e "${RED}❌ FAIL${NC}"
    FAILED_TESTS=$((FAILED_TESTS + 1))
fi
TOTAL_TESTS=$((TOTAL_TESTS + 1))

echo ""
echo -e "${BLUE}🔄 Testing Workflow Scenarios${NC}"

if [ "$ALERT_ID" != "null" ] && [ ! -z "$ALERT_ID" ]; then
    # Test response workflow
    echo -n "🔸 Adding response to alert... "
    response_result=$(curl -s -X POST "http://localhost:8002/api/v1/emergency/events/$ALERT_ID/respond" \
        -H "Authorization: Bearer $TOKEN" \
        -H "Content-Type: application/json" \
        -d '{
            "response_type": "help_on_way",
            "message": "Advanced test response",
            "eta_minutes": 20
        }')
    
    RESPONSE_ID=$(echo "$response_result" | jq -r '.id')
    if [ "$RESPONSE_ID" != "null" ] && [ ! -z "$RESPONSE_ID" ]; then
        echo -e "${GREEN}✅ PASS${NC} (Response ID: $RESPONSE_ID)"
        PASSED_TESTS=$((PASSED_TESTS + 1))
        
        # Test response appears in responses list
        test_advanced "Response appears in alert responses" \
            "curl -s -X GET 'http://localhost:8002/api/v1/alert/$ALERT_ID/responses' -H 'Authorization: Bearer $TOKEN' | jq '.[] | select(.id == $RESPONSE_ID) | .id'" \
            '[ "$result" = "$RESPONSE_ID" ]'
        
        # Test response data integrity
        test_advanced "Response ETA is preserved" \
            "curl -s -X GET 'http://localhost:8002/api/v1/alert/$ALERT_ID/responses' -H 'Authorization: Bearer $TOKEN' | jq '.[] | select(.id == $RESPONSE_ID) | .eta_minutes'" \
            '[ "$result" = "20" ]'
    else
        echo -e "${RED}❌ FAIL${NC}"
        FAILED_TESTS=$((FAILED_TESTS + 1))
    fi
    TOTAL_TESTS=$((TOTAL_TESTS + 1))
    
    # Test resolution workflow
    test_advanced "Alert resolution" \
        "curl -s -w '%{http_code}' -X PUT 'http://localhost:8002/api/v1/emergency/events/$ALERT_ID/resolve' -H 'Authorization: Bearer $TOKEN' | tail -c 3" \
        '[ "$result" = "200" ]'
    
    # Test resolved alert is not in active list
    test_advanced "Resolved alert not in active list" \
        "curl -s -X GET 'http://localhost:8002/api/v1/alerts/active' -H 'Authorization: Bearer $TOKEN' | jq '.[] | select(.id == $ALERT_ID) | .id'" \
        '[ -z "$result" ]'
fi

echo ""
echo -e "${BLUE}🌍 Testing Geographic Features${NC}"

# Test nearby functionality with different coordinates
test_advanced "Nearby alerts with Moscow coordinates" \
    "curl -s -X GET 'http://localhost:8002/api/v1/emergency/events/nearby?latitude=55.7558&longitude=37.6176&radius=1000' -H 'Authorization: Bearer $TOKEN' | jq 'type'" \
    '[ "$result" = "\"array\"" ]'

test_advanced "Nearby alerts with New York coordinates" \
    "curl -s -X GET 'http://localhost:8002/api/v1/emergency/events/nearby?latitude=40.7128&longitude=-74.0060&radius=1000' -H 'Authorization: Bearer $TOKEN' | jq 'type'" \
    '[ "$result" = "\"array\"" ]'

# Test with different radius values
test_advanced "Nearby alerts with small radius (100m)" \
    "curl -s -X GET 'http://localhost:8002/api/v1/emergency/events/nearby?latitude=55.7558&longitude=37.6176&radius=100' -H 'Authorization: Bearer $TOKEN' | jq 'type'" \
    '[ "$result" = "\"array\"" ]'

test_advanced "Nearby alerts with large radius (50km)" \
    "curl -s -X GET 'http://localhost:8002/api/v1/emergency/events/nearby?latitude=55.7558&longitude=37.6176&radius=50000' -H 'Authorization: Bearer $TOKEN' | jq 'type'" \
    '[ "$result" = "\"array\"" ]'

echo ""
echo -e "${BLUE}📈 Testing Statistics Accuracy${NC}"

# Get current stats
stats_before=$(curl -s -X GET "http://localhost:8002/api/v1/stats" -H "Authorization: Bearer $TOKEN")
total_before=$(echo "$stats_before" | jq -r '.total_alerts')
active_before=$(echo "$stats_before" | jq -r '.active_alerts')

echo "📊 Stats before: Total=$total_before, Active=$active_before"

# Create new alert
new_alert=$(curl -s -X POST "http://localhost:8002/api/v1/emergency/events" \
    -H "Authorization: Bearer $TOKEN" \
    -H "Content-Type: application/json" \
    -d '{
        "latitude": 55.7558,
        "longitude": 37.6176,
        "alert_type": "general",
        "message": "Stats test alert"
    }')

NEW_ALERT_ID=$(echo "$new_alert" | jq -r '.id')

# Get stats after
stats_after=$(curl -s -X GET "http://localhost:8002/api/v1/stats" -H "Authorization: Bearer $TOKEN")
total_after=$(echo "$stats_after" | jq -r '.total_alerts')
active_after=$(echo "$stats_after" | jq -r '.active_alerts')

echo "📊 Stats after: Total=$total_after, Active=$active_after"

test_advanced "Total alerts increased by 1" \
    "echo $((total_after - total_before))" \
    '[ "$result" = "1" ]'

test_advanced "Active alerts increased by 1" \
    "echo $((active_after - active_before))" \
    '[ "$result" = "1" ]'

echo ""
echo -e "${BLUE}🔐 Testing Security Edge Cases${NC}"

# Test with invalid token
test_advanced "Invalid token returns 401/403" \
    "curl -s -w '%{http_code}' -X GET 'http://localhost:8002/api/v1/stats' -H 'Authorization: Bearer invalid_token_123' | tail -c 3" \
    '[ "$result" = "403" ] || [ "$result" = "401" ]'

# Test with malformed token
test_advanced "Malformed token returns 401/403" \
    "curl -s -w '%{http_code}' -X GET 'http://localhost:8002/api/v1/stats' -H 'Authorization: Bearer not.a.jwt.token' | tail -c 3" \
    '[ "$result" = "403" ] || [ "$result" = "401" ]'

# Test with expired/old token format
test_advanced "Missing Bearer prefix returns 401/403" \
    "curl -s -w '%{http_code}' -X GET 'http://localhost:8002/api/v1/stats' -H 'Authorization: $TOKEN' | tail -c 3" \
    '[ "$result" = "403" ] || [ "$result" = "401" ]'

echo ""
echo "=" $(printf "%0.s=" {1..60})
echo -e "${BLUE}📊 ADVANCED TEST SUMMARY${NC}"
echo "=" $(printf "%0.s=" {1..60})
echo -e "Total Tests: ${YELLOW}$TOTAL_TESTS${NC}"
echo -e "Passed: ${GREEN}$PASSED_TESTS${NC}"
echo -e "Failed: ${RED}$FAILED_TESTS${NC}"

success_rate=$((PASSED_TESTS * 100 / TOTAL_TESTS))
echo -e "Success Rate: ${YELLOW}${success_rate}%${NC}"

if [ $FAILED_TESTS -eq 0 ]; then
    echo -e "${GREEN}🎉 ALL ADVANCED TESTS PASSED!${NC}"
    exit 0
elif [ $success_rate -ge 80 ]; then
    echo -e "${YELLOW}⚠️ Most tests passed. Minor issues detected.${NC}"
    exit 0
else
    echo -e "${RED}❌ Several advanced tests failed.${NC}"
    exit 1
fi