#!/bin/bash

echo "🚨 Testing Emergency Event Details API"
echo "=" $(printf "%0.s=" {1..50})

# Сначала получаем токен авторизации
echo "🔑 Getting authentication 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 "❌ Failed to authenticate"
    exit 1
fi

echo "✅ Authentication successful"

# Создаем тестовое событие
echo "📝 Creating test emergency event..."
EVENT_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": "general",
    "message": "Test emergency for detailed API",
    "address": "Test Address, Moscow",
    "contact_emergency_services": true,
    "notify_emergency_contacts": true
  }')

EVENT_ID=$(echo $EVENT_RESPONSE | jq -r '.id')

if [ "$EVENT_ID" = "null" ] || [ -z "$EVENT_ID" ]; then
    echo "❌ Failed to create emergency event"
    echo "Response: $EVENT_RESPONSE"
    exit 1
fi

echo "✅ Created emergency event with ID: $EVENT_ID"

# Добавляем ответ к событию
echo "💬 Adding response to the event..."
RESPONSE_DATA=$(curl -s -X POST "http://localhost:8002/api/v1/emergency/events/$EVENT_ID/respond" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "response_type": "help_on_way",
    "message": "Test response for API testing",
    "eta_minutes": 15
  }')

echo "✅ Added response to event"

# Тестируем получение детальной информации
echo ""
echo "🔍 Testing detailed event information API..."
DETAILED_RESPONSE=$(curl -s -X GET "http://localhost:8002/api/v1/emergency/events/$EVENT_ID" \
  -H "Authorization: Bearer $TOKEN")

echo "Response:"
echo $DETAILED_RESPONSE | jq '.'

# Тестируем получение краткой информации
echo ""
echo "📋 Testing brief event information API..."
BRIEF_RESPONSE=$(curl -s -X GET "http://localhost:8002/api/v1/emergency/events/$EVENT_ID/brief" \
  -H "Authorization: Bearer $TOKEN")

echo "Brief Response:"
echo $BRIEF_RESPONSE | jq '.'

echo ""
echo "=" $(printf "%0.s=" {1..50})
echo "🎯 Test completed!"
echo "Event ID for manual testing: $EVENT_ID"