#!/bin/bash

echo "🧪 Comprehensive Emergency Service API Testing"
echo "=" $(printf "%0.s=" {1..70})

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

# Counters
TOTAL_TESTS=0
PASSED_TESTS=0
FAILED_TESTS=0

# Function to test endpoint
test_endpoint() {
    local method="$1"
    local endpoint="$2"
    local expected_status="$3"
    local data="$4"
    local description="$5"
    
    TOTAL_TESTS=$((TOTAL_TESTS + 1))
    
    echo -n "🔸 Testing $description... "
    
    if [ "$method" = "GET" ]; then
        response=$(curl -s -w "%{http_code}" -X GET "http://localhost:8002$endpoint" \
            -H "Authorization: Bearer $TOKEN")
    elif [ "$method" = "POST" ]; then
        response=$(curl -s -w "%{http_code}" -X POST "http://localhost:8002$endpoint" \
            -H "Authorization: Bearer $TOKEN" \
            -H "Content-Type: application/json" \
            -d "$data")
    elif [ "$method" = "PUT" ]; then
        response=$(curl -s -w "%{http_code}" -X PUT "http://localhost:8002$endpoint" \
            -H "Authorization: Bearer $TOKEN" \
            -H "Content-Type: application/json" \
            -d "$data")
    elif [ "$method" = "DELETE" ]; then
        response=$(curl -s -w "%{http_code}" -X DELETE "http://localhost:8002$endpoint" \
            -H "Authorization: Bearer $TOKEN")
    fi
    
    status_code="${response: -3}"
    response_body="${response%???}"
    
    if [ "$status_code" = "$expected_status" ]; then
        echo -e "${GREEN}✅ PASS${NC} ($status_code)"
        PASSED_TESTS=$((PASSED_TESTS + 1))
    else
        echo -e "${RED}❌ FAIL${NC} (Expected: $expected_status, Got: $status_code)"
        echo "   Response: ${response_body:0:100}..."
        FAILED_TESTS=$((FAILED_TESTS + 1))
    fi
}

# Function to test endpoint without auth
test_endpoint_no_auth() {
    local method="$1"
    local endpoint="$2"
    local description="$3"
    
    TOTAL_TESTS=$((TOTAL_TESTS + 1))
    
    echo -n "🔸 Testing $description (no auth)... "
    
    response=$(curl -s -w "%{http_code}" -X $method "http://localhost:8002$endpoint")
    status_code="${response: -3}"
    
    if [ "$status_code" = "403" ] || [ "$status_code" = "401" ]; then
        echo -e "${GREEN}✅ PASS${NC} (Correctly requires auth: $status_code)"
        PASSED_TESTS=$((PASSED_TESTS + 1))
    else
        echo -e "${RED}❌ FAIL${NC} (Should require auth but got: $status_code)"
        FAILED_TESTS=$((FAILED_TESTS + 1))
    fi
}

# Get authentication token
echo "🔑 Getting authentication token..."
TOKEN_RESPONSE=$(curl -s -X POST "http://localhost:8001/api/v1/auth/login" \
  -H "Content-Type: application/json" \
  -d '{"username": "testuser", "password": "testpass"}')

TOKEN=$(echo "$TOKEN_RESPONSE" | jq -r '.access_token')

if [ "$TOKEN" = "null" ] || [ -z "$TOKEN" ]; then
    echo -e "${RED}❌ Failed to get authentication token${NC}"
    echo "Response: $TOKEN_RESPONSE"
    exit 1
fi

echo -e "${GREEN}✅ Authentication token obtained${NC}"
echo ""

# Test health endpoint (should not require auth)
echo -e "${BLUE}📊 Testing Health Endpoint${NC}"
TOTAL_TESTS=$((TOTAL_TESTS + 1))
health_response=$(curl -s -w "%{http_code}" "http://localhost:8002/health")
health_status="${health_response: -3}"
if [ "$health_status" = "200" ]; then
    echo -e "🔸 Health endpoint... ${GREEN}✅ PASS${NC} ($health_status)"
    PASSED_TESTS=$((PASSED_TESTS + 1))
else
    echo -e "🔸 Health endpoint... ${RED}❌ FAIL${NC} ($health_status)"
    FAILED_TESTS=$((FAILED_TESTS + 1))
fi
echo ""

# Test authentication requirements
echo -e "${BLUE}🔐 Testing Authentication Requirements${NC}"
test_endpoint_no_auth "GET" "/api/v1/stats" "Stats endpoint"
test_endpoint_no_auth "GET" "/api/v1/alerts/active" "Active alerts"
test_endpoint_no_auth "POST" "/api/v1/emergency/events" "Create emergency event"
echo ""

# Test basic endpoints with auth
echo -e "${BLUE}📊 Testing Statistics and Info Endpoints${NC}"
test_endpoint "GET" "/api/v1/stats" "200" "" "Statistics"
echo ""

# Test alert creation and management
echo -e "${BLUE}🆘 Testing Alert Creation and Management${NC}"

# Create an alert
alert_data='{
  "latitude": 55.7558,
  "longitude": 37.6176,
  "alert_type": "general",
  "message": "Test alert for comprehensive testing",
  "address": "Test Address, Moscow",
  "contact_emergency_services": true,
  "notify_emergency_contacts": true
}'

echo -n "🔸 Creating test alert... "
create_response=$(curl -s -X POST "http://localhost:8002/api/v1/emergency/events" \
    -H "Authorization: Bearer $TOKEN" \
    -H "Content-Type: application/json" \
    -d "$alert_data")

ALERT_ID=$(echo "$create_response" | jq -r '.id')
if [ "$ALERT_ID" != "null" ] && [ ! -z "$ALERT_ID" ]; then
    echo -e "${GREEN}✅ PASS${NC} (Alert ID: $ALERT_ID)"
    PASSED_TESTS=$((PASSED_TESTS + 1))
else
    echo -e "${RED}❌ FAIL${NC}"
    echo "Response: $create_response"
    FAILED_TESTS=$((FAILED_TESTS + 1))
fi
TOTAL_TESTS=$((TOTAL_TESTS + 1))

# Test alert retrieval if alert was created
if [ "$ALERT_ID" != "null" ] && [ ! -z "$ALERT_ID" ]; then
    echo ""
    echo -e "${BLUE}🔍 Testing Alert Retrieval Endpoints${NC}"
    test_endpoint "GET" "/api/v1/emergency/events/$ALERT_ID" "200" "" "Get alert details"
    test_endpoint "GET" "/api/v1/emergency/events/$ALERT_ID/brief" "200" "" "Get alert brief info"
    
    echo ""
    echo -e "${BLUE}📝 Testing Alert Response${NC}"
    response_data='{
      "response_type": "help_on_way",
      "message": "I am coming to help",
      "eta_minutes": 15
    }'
    test_endpoint "POST" "/api/v1/emergency/events/$ALERT_ID/respond" "200" "$response_data" "Respond to alert"
    
    echo ""
    echo -e "${BLUE}✅ Testing Alert Resolution${NC}"
    test_endpoint "PUT" "/api/v1/emergency/events/$ALERT_ID/resolve" "200" "" "Resolve alert"
fi

echo ""
echo -e "${BLUE}📋 Testing List Endpoints${NC}"
test_endpoint "GET" "/api/v1/alerts/active" "200" "" "Active alerts"
test_endpoint "GET" "/api/v1/alerts/my" "200" "" "My alerts"
test_endpoint "GET" "/api/v1/emergency/events/my" "200" "" "My emergency events"
test_endpoint "GET" "/api/v1/emergency/events/nearby?latitude=55.7558&longitude=37.6176" "200" "" "Nearby events"

echo ""
echo -e "${BLUE}📊 Testing Reports Endpoints${NC}"
test_endpoint "GET" "/api/v1/reports" "200" "" "Get reports"
test_endpoint "GET" "/api/v1/emergency/reports" "200" "" "Get emergency reports"

# Test report creation
report_data='{
  "latitude": 55.7558,
  "longitude": 37.6176,
  "report_type": "unsafe_area",
  "description": "Test report for comprehensive testing",
  "address": "Test Address, Moscow",
  "is_anonymous": false,
  "severity": 3
}'
test_endpoint "POST" "/api/v1/report" "200" "$report_data" "Create report"

echo ""
echo -e "${BLUE}🛡️ Testing Safety Check Endpoints${NC}"
safety_check_data='{
  "latitude": 55.7558,
  "longitude": 37.6176,
  "status": "safe",
  "message": "I am safe, just checking in"
}'
test_endpoint "POST" "/api/v1/safety-check" "200" "$safety_check_data" "Create safety check"
test_endpoint "GET" "/api/v1/safety-checks" "200" "" "Get safety checks"

echo ""
echo -e "${BLUE}🌐 Testing WebSocket Management Endpoints${NC}"
test_endpoint "GET" "/api/v1/websocket/stats" "200" "" "WebSocket stats"
test_endpoint "GET" "/api/v1/websocket/connections" "200" "" "WebSocket connections"

# Test deprecated alert endpoints for backward compatibility
echo ""
echo -e "${BLUE}🔄 Testing Legacy Alert Endpoints${NC}"
test_endpoint "GET" "/api/v1/alerts/nearby?latitude=55.7558&longitude=37.6176" "200" "" "Nearby alerts (legacy)"

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

if [ $FAILED_TESTS -eq 0 ]; then
    echo -e "${GREEN}🎉 ALL TESTS PASSED!${NC}"
    exit 0
else
    echo -e "${RED}❌ Some tests failed. Check the output above.${NC}"
    exit 1
fi