#!/bin/bash

# Women Safety App - Gateway API Testing Script (Simplified)
# This version sends all requests through 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

echo -e "${BLUE}=======================================${NC}"
echo -e "${BLUE}🔍 Women Safety App Gateway API Test ${NC}"
echo -e "${BLUE}=======================================${NC}"

# Base URL - все запросы идут через API Gateway
GATEWAY_URL="http://localhost:8000"

# Проверка, запущен ли API Gateway
echo -e "${YELLOW}🔎 Checking API Gateway...${NC}"
if curl -s "$GATEWAY_URL/api/v1/health" | grep -q "status.*healthy"; then
    echo -e "${GREEN}✅ API Gateway is running${NC}"
else
    echo -e "${RED}❌ API Gateway is not available. Make sure it's running before testing.${NC}"
    exit 1
fi

# Регистрация пользователя
echo -e "\n${YELLOW}👤 Registering test user...${NC}"
# Создаем уникальное имя пользователя и email с временной меткой
TIMESTAMP=$(date +%s)
USERNAME="testgateway_${TIMESTAMP}"
EMAIL="testgateway_${TIMESTAMP}@example.com"

echo -e "  └─ Using username: $USERNAME and email: $EMAIL"

REGISTER_RESPONSE=$(curl -s -X POST "$GATEWAY_URL/api/v1/auth/register" \
    -H "Content-Type: application/json" \
    -d '{
        "username": "'"$USERNAME"'",
        "email": "'"$EMAIL"'",
        "password": "Test@1234",
        "full_name": "Test Gateway User",
        "phone_number": "+1234567890"
    }')

echo "$REGISTER_RESPONSE" | jq
USER_ID=$(echo "$REGISTER_RESPONSE" | jq -r '.id')

# Авторизация
echo -e "\n${YELLOW}🔑 Logging in as test user...${NC}"
LOGIN_RESPONSE=$(curl -s -X POST "$GATEWAY_URL/api/v1/auth/login" \
    -H "Content-Type: application/json" \
    -d '{
        "username": "'"$USERNAME"'",
        "password": "Test@1234"
    }')

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

if [ "$TOKEN" != "null" ] && [ -n "$TOKEN" ]; then
    echo -e "${GREEN}✅ Login successful${NC}"
else
    echo -e "${RED}❌ Login failed, stopping test${NC}"
    exit 1
fi

# Получение информации о пользователе
echo -e "\n${YELLOW}👤 Getting user profile...${NC}"
curl -s -X GET "$GATEWAY_URL/api/v1/users/me" \
    -H "Authorization: Bearer $TOKEN" | jq

# Обновление местоположения
echo -e "\n${YELLOW}📍 Updating location...${NC}"
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
    }' | jq

# Создание экстренного оповещения
echo -e "\n${YELLOW}🚨 Creating emergency alert...${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": "Gateway test emergency alert"
    }')

echo "$ALERT_RESPONSE" | jq
ALERT_ID=$(echo "$ALERT_RESPONSE" | jq -r '.id')

# Получение текущих оповещений
echo -e "\n${YELLOW}🔔 Getting active alerts...${NC}"
curl -s -X GET "$GATEWAY_URL/api/v1/emergency/alerts/my" \
    -H "Authorization: Bearer $TOKEN" | jq

# Отмена оповещения
if [ "$ALERT_ID" != "null" ] && [ -n "$ALERT_ID" ]; then
    echo -e "\n${YELLOW}🚫 Cancelling alert...${NC}"
    curl -s -X PATCH "$GATEWAY_URL/api/v1/emergency/alerts/$ALERT_ID/cancel" \
        -H "Authorization: Bearer $TOKEN" | jq
fi

# Проверка доступа к панели пользователя (комплексный запрос)
echo -e "\n${YELLOW}📊 Getting user dashboard...${NC}"
curl -s -X GET "$GATEWAY_URL/api/v1/users/dashboard" \
    -H "Authorization: Bearer $TOKEN" | jq

echo -e "\n${GREEN}✅ Gateway API test completed${NC}"