# API Documentation - Women's Safety App

## Overview

The Women's Safety App provides a comprehensive API for managing user profiles, emergency alerts, location services, and health calendar functionality.

**Base URL:** `http://localhost:8000` (API Gateway)

## Swagger Documentation

Интерактивная документация API доступна через Swagger UI по следующим URL:

- API Gateway: `http://localhost:8000/docs`
- User Service: `http://localhost:8001/docs`
- Emergency Service: `http://localhost:8002/docs`
- Location Service: `http://localhost:8003/docs`
- Calendar Service: `http://localhost:8004/docs`
- Notification Service: `http://localhost:8005/docs`
- Nutrition Service: `http://localhost:8006/docs`

Документация в формате ReDoc доступна по адресам:

- API Gateway: `http://localhost:8000/redoc`
- User Service: `http://localhost:8001/redoc`
- (и т.д. для остальных сервисов)

> **Примечание**: Swagger-документация для каждого сервиса доступна только при запущенном соответствующем сервисе. Если сервис не запущен, страница документации будет недоступна.

## Authentication

All endpoints except registration and login require JWT authentication.

**Headers:**
```
Authorization: Bearer <jwt_token>
```

### Testing with Swagger UI

Для тестирования API через Swagger UI:

1. Запустите необходимые сервисы:
   ```bash
   ./start_services.sh
   ```

2. Откройте Swagger UI в браузере:
   ```
   http://localhost:8000/docs
   ```

3. Получите JWT-токен через эндпоинты `/api/v1/auth/login` или `/api/v1/auth/register`

4. Авторизуйтесь в Swagger UI:
   - Нажмите на кнопку "Authorize" в правом верхнем углу
   - Введите полученный JWT-токен в формате: `Bearer <token>`
   - Нажмите "Authorize"

5. Теперь вы можете тестировать все защищенные эндпоинты

## API Endpoints

### 🔐 Authentication

#### Register User
```http
POST /api/v1/register
```

**Body:**
```json
{
  "email": "user@example.com",
  "password": "password123",
  "first_name": "John",
  "last_name": "Doe",
  "phone": "+1234567890"
}
```

#### Login
```http
POST /api/v1/login
```

**Body:**
```json
{
  "email": "user@example.com",
  "password": "password123"
}
```

**Response:**
```json
{
  "access_token": "jwt_token_here",
  "token_type": "bearer"
}
```

### 👤 User Profile

#### Get Profile
```http
GET /api/v1/profile
Authorization: Bearer <token>
```

#### Update Profile
```http
PUT /api/v1/profile
Authorization: Bearer <token>
```

**Body:**
```json
{
  "first_name": "Jane",
  "bio": "Updated bio",
  "emergency_contact_1_name": "Emergency Contact",
  "emergency_contact_1_phone": "+1234567890"
}
```

### 🚨 Emergency Services

#### Create Emergency Alert
```http
POST /api/v1/alert
Authorization: Bearer <token>
```

**Body:**
```json
{
  "latitude": 37.7749,
  "longitude": -122.4194,
  "alert_type": "general",
  "message": "Need help immediately",
  "address": "123 Main St, City"
}
```

#### Respond to Alert
```http
POST /api/v1/alert/{alert_id}/respond
Authorization: Bearer <token>
```

**Body:**
```json
{
  "response_type": "help_on_way",
  "message": "I'm coming to help",
  "eta_minutes": 10
}
```

#### Resolve Alert
```http
PUT /api/v1/alert/{alert_id}/resolve
Authorization: Bearer <token>
```

#### Get My Alerts
```http
GET /api/v1/alerts/my
Authorization: Bearer <token>
```

#### Get Active Alerts
```http
GET /api/v1/alerts/active
Authorization: Bearer <token>
```

### 📍 Location Services

#### Update Location
```http
POST /api/v1/update-location
Authorization: Bearer <token>
```

**Body:**
```json
{
  "latitude": 37.7749,
  "longitude": -122.4194,
  "accuracy": 10.5
}
```

#### Get User Location
```http
GET /api/v1/user-location/{user_id}
Authorization: Bearer <token>
```

#### Find Nearby Users
```http
GET /api/v1/nearby-users?latitude=37.7749&longitude=-122.4194&radius_km=1.0
Authorization: Bearer <token>
```

#### Get Location History
```http
GET /api/v1/location-history?hours=24
Authorization: Bearer <token>
```

### 📅 Calendar Services

#### Create Calendar Entry
```http
POST /api/v1/entries
Authorization: Bearer <token>
```

**Body:**
```json
{
  "entry_date": "2024-01-15",
  "entry_type": "period",
  "flow_intensity": "medium",
  "mood": "happy",
  "energy_level": 4
}
```

#### Get Calendar Entries
```http
GET /api/v1/entries?start_date=2024-01-01&end_date=2024-01-31
Authorization: Bearer <token>
```

#### Get Cycle Overview
```http
GET /api/v1/cycle-overview
Authorization: Bearer <token>
```

**Response:**
```json
{
  "current_cycle_day": 15,
  "current_phase": "luteal",
  "next_period_date": "2024-02-01",
  "days_until_period": 7,
  "cycle_regularity": "regular",
  "avg_cycle_length": 28
}
```

#### Get Health Insights
```http
GET /api/v1/insights
Authorization: Bearer <token>
```

### 🔔 Notification Services

#### Register Device Token
```http
POST /api/v1/register-device
Authorization: Bearer <token>
```

**Body:**
```json
{
  "token": "fcm_device_token_here",
  "platform": "android"
}
```

#### Send Notification
```http
POST /api/v1/send-notification?target_user_id=123
Authorization: Bearer <token>
```

**Body:**
```json
{
  "title": "Hello!",
  "body": "This is a test notification",
  "priority": "normal"
}
```

### 🍎 Nutrition Services

#### Search Food Items
```http
GET /api/v1/nutrition/foods?query=apple
Authorization: Bearer <token>
```

**Response:**
```json
{
  "results": [
    {
      "food_id": "123456",
      "name": "Apple, raw, with skin",
      "brand": "",
      "calories": 52,
      "serving_size": "100g",
      "nutrients": {
        "carbohydrates": 13.8,
        "protein": 0.3,
        "fat": 0.2,
        "fiber": 2.4
      }
    },
    {
      "food_id": "789012",
      "name": "Apple juice, unsweetened",
      "brand": "Example Brand",
      "calories": 46,
      "serving_size": "100ml",
      "nutrients": {
        "carbohydrates": 11.2,
        "protein": 0.1,
        "fat": 0.1,
        "fiber": 0.2
      }
    }
  ]
}
```

#### Add Nutrition Entry
```http
POST /api/v1/nutrition/entries
Authorization: Bearer <token>
```

**Body:**
```json
{
  "food_id": "123456",
  "date": "2025-10-16",
  "meal_type": "lunch",
  "quantity": 1.0,
  "serving_size": "100g",
  "notes": "Red apple"
}
```

#### Get Daily Nutrition Summary
```http
GET /api/v1/nutrition/daily-summary?date=2025-10-16
Authorization: Bearer <token>
```

**Response:**
```json
{
  "date": "2025-10-16",
  "total_calories": 1578,
  "total_carbohydrates": 175.3,
  "total_proteins": 78.2,
  "total_fats": 52.8,
  "total_water": 1200,
  "entries": [
    {
      "id": 123,
      "food_name": "Apple, raw, with skin",
      "meal_type": "lunch",
      "calories": 52,
      "quantity": 1.0,
      "serving_size": "100g"
    }
  ]
}
```

#### Track Water Intake
```http
POST /api/v1/nutrition/water
Authorization: Bearer <token>
```

**Body:**
```json
{
  "date": "2025-10-16",
  "amount_ml": 250,
  "time": "12:30:00"
}
```

### 📊 System Status

#### Check Service Health
```http
GET /api/v1/health
```

#### Check All Services Status
```http
GET /api/v1/services-status
```

## Error Responses

All endpoints return errors in the following format:

```json
{
  "detail": "Error message here"
}
```

### Common HTTP Status Codes

- `200` - Success
- `201` - Created
- `400` - Bad Request
- `401` - Unauthorized
- `403` - Forbidden
- `404` - Not Found
- `422` - Validation Error
- `429` - Rate Limited
- `500` - Internal Server Error
- `503` - Service Unavailable

## Rate Limiting

API Gateway implements rate limiting:
- **100 requests per minute** per IP address
- Emergency endpoints have higher priority

## Data Models

### User
```json
{
  "id": 1,
  "uuid": "550e8400-e29b-41d4-a716-446655440000",
  "email": "user@example.com",
  "first_name": "John",
  "last_name": "Doe",
  "phone": "+1234567890",
  "location_sharing_enabled": true,
  "emergency_notifications_enabled": true,
  "email_verified": false,
  "is_active": true
}
```

### Emergency Alert
```json
{
  "id": 1,
  "uuid": "550e8400-e29b-41d4-a716-446655440001",
  "user_id": 1,
  "latitude": 37.7749,
  "longitude": -122.4194,
  "alert_type": "general",
  "message": "Need help",
  "is_resolved": false,
  "notified_users_count": 15,
  "responded_users_count": 3,
  "created_at": "2024-01-15T10:30:00Z"
}
```

### Location
```json
{
  "user_id": 1,
  "latitude": 37.7749,
  "longitude": -122.4194,
  "accuracy": 10.5,
  "updated_at": "2024-01-15T10:30:00Z"
}
```

## WebSocket Events (Future Enhancement)

Real-time notifications for emergency alerts:

```javascript
// Connect to WebSocket
const ws = new WebSocket('ws://localhost:8000/ws/alerts');

// Listen for emergency alerts
ws.onmessage = function(event) {
    const alert = JSON.parse(event.data);
    // Handle emergency alert
};
```

## SDK Examples

### JavaScript/TypeScript
```javascript
class WomenSafetyAPI {
  constructor(baseUrl, token) {
    this.baseUrl = baseUrl;
    this.token = token;
  }

  async createAlert(alertData) {
    const response = await fetch(`${this.baseUrl}/api/v1/alert`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${this.token}`
      },
      body: JSON.stringify(alertData)
    });
    return response.json();
  }
}
```

### Python
```python
import httpx

class WomenSafetyAPI:
    def __init__(self, base_url: str, token: str):
        self.base_url = base_url
        self.headers = {"Authorization": f"Bearer {token}"}

    async def create_alert(self, alert_data: dict):
        async with httpx.AsyncClient() as client:
            response = await client.post(
                f"{self.base_url}/api/v1/alert",
                json=alert_data,
                headers=self.headers
            )
            return response.json()
```