#!/bin/bash

# Скрипт для тестирования всех API-эндпоинтов через API Gateway

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

# База URL API Gateway
GATEWAY_URL="http://localhost:8000"

# Функция для проверки статуса ответа
check_status() {
    local response=$1
    local endpoint=$2
    
    if echo "$response" | grep -q "\"status\"\|\"id\"\|\"message\""; then
        echo -e "${GREEN}✅ $endpoint - OK${NC}"
        return 0
    else
        echo -e "${RED}❌ $endpoint - Error: $response${NC}"
        return 1
    fi
}

# Проверка доступности API Gateway
echo -e "${BLUE}===============================================${NC}"
echo -e "${BLUE}🔍 Проверка API Gateway и всех маршрутов${NC}"
echo -e "${BLUE}===============================================${NC}"

echo -e "${YELLOW}🔎 Проверка API Gateway...${NC}"
HEALTH_RESPONSE=$(curl -s "$GATEWAY_URL/api/v1/health")
if echo "$HEALTH_RESPONSE" | grep -q "healthy"; then
    echo -e "${GREEN}✅ API Gateway работает${NC}"
else
    echo -e "${RED}❌ API Gateway недоступен. Убедитесь, что он запущен.${NC}"
    exit 1
fi

echo -e "\n${BLUE}==== User Service Endpoints ====${NC}"

# Регистрация тестового пользователя
echo -e "${YELLOW}→ Тестирование /api/v1/auth/register${NC}"
REGISTER_RESPONSE=$(curl -s -X POST "$GATEWAY_URL/api/v1/auth/register" \
    -H "Content-Type: application/json" \
    -d '{
        "username": "test_endpoints",
        "email": "test_endpoints@example.com",
        "password": "Test@1234",
        "full_name": "Test Endpoints User",
        "phone_number": "+7123456789"
    }')
check_status "$REGISTER_RESPONSE" "/api/v1/auth/register"
USER_ID=$(echo "$REGISTER_RESPONSE" | grep -o '"id":"[^"]*"' | cut -d'"' -f4)
if [ -n "$USER_ID" ]; then
    echo -e "  └─ Создан пользователь с ID: $USER_ID"
else
    echo -e "  └─ Не удалось получить ID пользователя"
fi

# Авторизация
echo -e "${YELLOW}→ Тестирование /api/v1/auth/login${NC}"
LOGIN_RESPONSE=$(curl -s -X POST "$GATEWAY_URL/api/v1/auth/login" \
    -H "Content-Type: application/json" \
    -d '{
        "username": "test_endpoints",
        "password": "Test@1234"
    }')
check_status "$LOGIN_RESPONSE" "/api/v1/auth/login"
TOKEN=$(echo "$LOGIN_RESPONSE" | grep -o '"access_token":"[^"]*"' | cut -d'"' -f4)

if [ -z "$TOKEN" ]; then
    echo -e "${RED}❌ Не удалось получить токен авторизации. Дальнейшие тесты невозможны.${NC}"
    exit 1
fi

# Получение профиля пользователя
echo -e "${YELLOW}→ Тестирование /api/v1/users/me${NC}"
ME_RESPONSE=$(curl -s -X GET "$GATEWAY_URL/api/v1/users/me" \
    -H "Authorization: Bearer $TOKEN")
check_status "$ME_RESPONSE" "/api/v1/users/me"

# Изменение пароля
echo -e "${YELLOW}→ Тестирование /api/v1/users/me/change-password${NC}"
PASSWORD_RESPONSE=$(curl -s -X POST "$GATEWAY_URL/api/v1/users/me/change-password" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $TOKEN" \
    -d '{
        "current_password": "Test@1234",
        "new_password": "Test@5678"
    }')
check_status "$PASSWORD_RESPONSE" "/api/v1/users/me/change-password"

# Получение дашборда
echo -e "${YELLOW}→ Тестирование /api/v1/users/dashboard${NC}"
DASH_RESPONSE=$(curl -s -X GET "$GATEWAY_URL/api/v1/users/dashboard" \
    -H "Authorization: Bearer $TOKEN")
check_status "$DASH_RESPONSE" "/api/v1/users/dashboard"

echo -e "\n${BLUE}==== Location Service Endpoints ====${NC}"

# Обновление местоположения
echo -e "${YELLOW}→ Тестирование /api/v1/locations/update${NC}"
LOCATION_RESPONSE=$(curl -s -X POST "$GATEWAY_URL/api/v1/locations/update" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $TOKEN" \
    -d '{
        "latitude": 55.7558,
        "longitude": 37.6173,
        "accuracy": 5.0
    }')
check_status "$LOCATION_RESPONSE" "/api/v1/locations/update"

# Получение последнего местоположения
echo -e "${YELLOW}→ Тестирование /api/v1/locations/last${NC}"
LAST_RESPONSE=$(curl -s -X GET "$GATEWAY_URL/api/v1/locations/last" \
    -H "Authorization: Bearer $TOKEN")
check_status "$LAST_RESPONSE" "/api/v1/locations/last"

# История местоположений
echo -e "${YELLOW}→ Тестирование /api/v1/locations/history${NC}"
HISTORY_RESPONSE=$(curl -s -X GET "$GATEWAY_URL/api/v1/locations/history" \
    -H "Authorization: Bearer $TOKEN")
check_status "$HISTORY_RESPONSE" "/api/v1/locations/history"

echo -e "\n${BLUE}==== Emergency Service Endpoints ====${NC}"

# Создание тревожного оповещения
echo -e "${YELLOW}→ Тестирование /api/v1/emergency/alerts${NC}"
ALERT_RESPONSE=$(curl -s -X POST "$GATEWAY_URL/api/v1/emergency/alerts" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $TOKEN" \
    -d '{
        "latitude": 55.7558,
        "longitude": 37.6173,
        "alert_type": "SOS",
        "message": "Endpoint test alert"
    }')
check_status "$ALERT_RESPONSE" "/api/v1/emergency/alerts POST"
ALERT_ID=$(echo "$ALERT_RESPONSE" | grep -o '"id":"[^"]*"' | cut -d'"' -f4)

# Получение своих оповещений
echo -e "${YELLOW}→ Тестирование /api/v1/emergency/alerts/my${NC}"
MY_ALERTS_RESPONSE=$(curl -s -X GET "$GATEWAY_URL/api/v1/emergency/alerts/my" \
    -H "Authorization: Bearer $TOKEN")
check_status "$MY_ALERTS_RESPONSE" "/api/v1/emergency/alerts/my"

# Отмена тревожного оповещения
if [ -n "$ALERT_ID" ]; then
    echo -e "${YELLOW}→ Тестирование /api/v1/emergency/alerts/$ALERT_ID/cancel${NC}"
    CANCEL_RESPONSE=$(curl -s -X PATCH "$GATEWAY_URL/api/v1/emergency/alerts/$ALERT_ID/cancel" \
        -H "Content-Type: application/json" \
        -H "Authorization: Bearer $TOKEN" \
        -d '{"reason": "Test completed"}')
    check_status "$CANCEL_RESPONSE" "/api/v1/emergency/alerts/$ALERT_ID/cancel"
fi

echo -e "\n${BLUE}==== Calendar Service Endpoints ====${NC}"

# Получение записей календаря
echo -e "${YELLOW}→ Тестирование /api/v1/calendar/entries${NC}"
ENTRIES_RESPONSE=$(curl -s -X GET "$GATEWAY_URL/api/v1/calendar/entries" \
    -H "Authorization: Bearer $TOKEN")
check_status "$ENTRIES_RESPONSE" "/api/v1/calendar/entries GET"

# Создание записи календаря
echo -e "${YELLOW}→ Тестирование /api/v1/calendar/entries POST${NC}"
ENTRY_RESPONSE=$(curl -s -X POST "$GATEWAY_URL/api/v1/calendar/entries" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $TOKEN" \
    -d '{
        "date": "2025-09-25",
        "mood": "good",
        "symptoms": ["headache", "fatigue"],
        "notes": "Test entry"
    }')
check_status "$ENTRY_RESPONSE" "/api/v1/calendar/entries POST"
ENTRY_ID=$(echo "$ENTRY_RESPONSE" | grep -o '"id":"[^"]*"' | cut -d'"' -f4)
if [ -n "$ENTRY_ID" ]; then
    echo -e "  └─ Создана запись календаря с ID: $ENTRY_ID"
else
    echo -e "  └─ Не удалось получить ID записи календаря"
fi

# Получение обзора цикла
echo -e "${YELLOW}→ Тестирование /api/v1/calendar/cycle-overview${NC}"
CYCLE_RESPONSE=$(curl -s -X GET "$GATEWAY_URL/api/v1/calendar/cycle-overview" \
    -H "Authorization: Bearer $TOKEN")
check_status "$CYCLE_RESPONSE" "/api/v1/calendar/cycle-overview"

# Получение настроек календаря
echo -e "${YELLOW}→ Тестирование /api/v1/calendar/settings${NC}"
SETTINGS_RESPONSE=$(curl -s -X GET "$GATEWAY_URL/api/v1/calendar/settings" \
    -H "Authorization: Bearer $TOKEN")
check_status "$SETTINGS_RESPONSE" "/api/v1/calendar/settings"

echo -e "\n${BLUE}==== Notification Service Endpoints ====${NC}"

# Регистрация устройства
echo -e "${YELLOW}→ Тестирование /api/v1/notifications/devices${NC}"
DEVICE_RESPONSE=$(curl -s -X POST "$GATEWAY_URL/api/v1/notifications/devices" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $TOKEN" \
    -d '{
        "device_token": "test-device-token-endpoint-test",
        "device_type": "android",
        "device_name": "Test Device"
    }')
check_status "$DEVICE_RESPONSE" "/api/v1/notifications/devices POST"
DEVICE_ID=$(echo "$DEVICE_RESPONSE" | grep -o '"id":"[^"]*"' | cut -d'"' -f4)
if [ -n "$DEVICE_ID" ]; then
    echo -e "  └─ Зарегистрировано устройство с ID: $DEVICE_ID"
else
    echo -e "  └─ Не удалось получить ID устройства"
fi

# Получение устройств
echo -e "${YELLOW}→ Тестирование /api/v1/notifications/devices GET${NC}"
DEVICES_RESPONSE=$(curl -s -X GET "$GATEWAY_URL/api/v1/notifications/devices" \
    -H "Authorization: Bearer $TOKEN")
check_status "$DEVICES_RESPONSE" "/api/v1/notifications/devices GET"

# Тестовое уведомление
echo -e "${YELLOW}→ Тестирование /api/v1/notifications/test${NC}"
TEST_RESPONSE=$(curl -s -X POST "$GATEWAY_URL/api/v1/notifications/test" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $TOKEN" \
    -d '{
        "title": "Test Notification",
        "body": "This is a test notification"
    }')
check_status "$TEST_RESPONSE" "/api/v1/notifications/test"

# История уведомлений
echo -e "${YELLOW}→ Тестирование /api/v1/notifications/history${NC}"
HISTORY_RESPONSE=$(curl -s -X GET "$GATEWAY_URL/api/v1/notifications/history" \
    -H "Authorization: Bearer $TOKEN")
check_status "$HISTORY_RESPONSE" "/api/v1/notifications/history"

echo -e "\n${BLUE}==== Проверка общей доступности сервисов ====${NC}"

# Получение статуса всех сервисов
echo -e "${YELLOW}→ Тестирование /api/v1/services-status${NC}"
STATUS_RESPONSE=$(curl -s -X GET "$GATEWAY_URL/api/v1/services-status")
check_status "$STATUS_RESPONSE" "/api/v1/services-status"

echo -e "\n${GREEN}✅ Тестирование эндпоинтов завершено${NC}"