#!/bin/bash

# Women Safety App - API Testing Script

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

echo -e "${BLUE}=======================================${NC}"
echo -e "${BLUE}🔍 Women Safety App API Testing Script ${NC}"
echo -e "${BLUE}=======================================${NC}"

# Base URLs
GATEWAY_URL="http://localhost:8000"
USER_URL="http://localhost:8001"
EMERGENCY_URL="http://localhost:8002"
LOCATION_URL="http://localhost:8003"
CALENDAR_URL="http://localhost:8004"
NOTIFICATION_URL="http://localhost:8005"

# Check if services are running
check_service() {
    local url=$1
    local service_name=$2
    
    echo -e "${YELLOW}🔎 Checking $service_name service...${NC}"
    # Проверяем оба возможных эндпоинта health
    if curl -s "$url/health" | grep -q "status.*healthy" || curl -s "$url/api/v1/health" | grep -q "status.*healthy"; then
        echo -e "${GREEN}✅ $service_name is running${NC}"
        return 0
    else
        echo -e "${RED}❌ $service_name is not available${NC}"
        return 1
    fi
}

# Test all services health
test_health() {
    echo -e "${BLUE}📊 Testing service health endpoints...${NC}"
    
    local errors=0
    check_service "$GATEWAY_URL" "API Gateway" || ((errors++))
    check_service "$USER_URL" "User Service" || ((errors++))
    check_service "$EMERGENCY_URL" "Emergency Service" || ((errors++))
    check_service "$LOCATION_URL" "Location Service" || ((errors++))
    check_service "$CALENDAR_URL" "Calendar Service" || ((errors++))
    check_service "$NOTIFICATION_URL" "Notification Service" || ((errors++))
    
    if [ $errors -eq 0 ]; then
        echo -e "${GREEN}✅ All services are healthy${NC}"
    else
        echo -e "${RED}❌ $errors service(s) are not running properly${NC}"
    fi
}

# Register a test user
register_user() {
    echo -e "${YELLOW}👤 Registering test user...${NC}"
    local response
    response=$(curl -s -X POST "$GATEWAY_URL/api/v1/auth/register" \
        -H "Content-Type: application/json" \
        -d '{
            "username": "testuser",
            "email": "test@example.com",
            "password": "Test@1234",
            "full_name": "Test User",
            "phone_number": "+1234567890"
        }')
    
    echo "$response" | jq
    if echo "$response" | grep -q "id"; then
        echo -e "${GREEN}✅ User registered successfully${NC}"
    else
        echo -e "${RED}❌ Failed to register user${NC}"
    fi
}

# Login with test user
login_user() {
    echo -e "${YELLOW}🔑 Logging in as test user...${NC}"
    local response
    response=$(curl -s -X POST "$GATEWAY_URL/api/v1/auth/login" \
        -H "Content-Type: application/json" \
        -d '{
            "username": "testuser",
            "password": "Test@1234"
        }')
    
    echo "$response" | jq
    
    # Extract token
    TOKEN=$(echo "$response" | jq -r '.access_token')
    if [ "$TOKEN" != "null" ] && [ -n "$TOKEN" ]; then
        echo -e "${GREEN}✅ Login successful${NC}"
        return 0
    else
        echo -e "${RED}❌ Login failed${NC}"
        return 1
    fi
}

# Test emergency alert
create_emergency() {
    if [ -z "$TOKEN" ]; then
        echo -e "${RED}❌ No token available. Please login first.${NC}"
        return 1
    fi
    
    echo -e "${YELLOW}🚨 Creating emergency alert...${NC}"
    local response
    response=$(curl -s -X POST "$GATEWAY_URL/api/v1/emergency/alerts" \
        -H "Content-Type: application/json" \
        -H "Authorization: Bearer $TOKEN" \
        -d '{
            "latitude": 37.7749,
            "longitude": -122.4194,
            "alert_type": "SOS",
            "message": "This is a test emergency alert"
        }')
    
    echo "$response" | jq
    
    if echo "$response" | grep -q "id"; then
        echo -e "${GREEN}✅ Emergency alert created successfully${NC}"
        # Extract emergency ID
        EMERGENCY_ID=$(echo "$response" | jq -r '.id')
        return 0
    else
        echo -e "${RED}❌ Failed to create emergency alert${NC}"
        return 1
    fi
}

# Test updating location
update_location() {
    if [ -z "$TOKEN" ]; then
        echo -e "${RED}❌ No token available. Please login first.${NC}"
        return 1
    fi
    
    echo -e "${YELLOW}📍 Updating user location...${NC}"
    local response
    response=$(curl -s -X POST "$GATEWAY_URL/api/v1/locations/update" \
        -H "Content-Type: application/json" \
        -H "Authorization: Bearer $TOKEN" \
        -d '{
            "latitude": 37.7749,
            "longitude": -122.4194,
            "accuracy": 10.0
        }')
    
    echo "$response" | jq
    
    if echo "$response" | grep -q "success"; then
        echo -e "${GREEN}✅ Location updated successfully${NC}"
        return 0
    else
        echo -e "${RED}❌ Failed to update location${NC}"
        return 1
    fi
}

# Main test sequence
run_tests() {
    test_health
    echo -e "${BLUE}---------------------------------------${NC}"
    
    register_user
    echo -e "${BLUE}---------------------------------------${NC}"
    
    login_user
    echo -e "${BLUE}---------------------------------------${NC}"
    
    if [ -n "$TOKEN" ]; then
        update_location
        echo -e "${BLUE}---------------------------------------${NC}"
        
        create_emergency
        echo -e "${BLUE}---------------------------------------${NC}"
    fi
    
    echo -e "${BLUE}✨ API testing completed${NC}"
    echo -e "${YELLOW}📖 API Documentation available at: ${GREEN}http://localhost:8000/docs${NC}"
}

# Check for jq dependency
if ! command -v jq &> /dev/null; then
    echo -e "${RED}❌ jq is required but not installed. Please install jq to continue.${NC}"
    echo -e "Run: ${YELLOW}sudo apt-get install jq${NC} (Debian/Ubuntu)"
    echo -e "or: ${YELLOW}brew install jq${NC} (macOS)"
    exit 1
fi

# Run tests
run_tests