# SIM Analytics API v1.1.3

## Overview
The SIM Analytics API provides comprehensive programmatic access to all features of the SIM Analytics platform. It supports two authentication levels and enables external systems to integrate seamlessly with client and SIM card management.

## 🚀 Quick Start

### Base URL
```
http://your-domain:5001/api/v1
```

### Authentication
Include your API key in the request headers:
```http
X-API-Key: your_api_key_here
```
or
```http
Authorization: Bearer your_api_key_here
```

### API Key Types
- **Admin API Key**: Full access (Create, Read, Update, Delete)
  - Format: `ska_admin_[32-character-string]`
  - Can create clients and SIM cards
  - Access to all analytics and management features

- **User API Key**: Read-only access
  - Format: `ska_user_[32-character-string]`
  - View clients, SIM cards, and analytics only
  - Cannot create, modify, or delete data

## 📚 Core Endpoints

### Health Check
```http
GET /api/v1/health
```
No authentication required.

### Client Management

#### List Clients
```http
GET /api/v1/clients
```
**Auth**: User or Admin

#### Create Client
```http
POST /api/v1/clients
Content-Type: application/json

{
    "client_name": "John Smith Corporation"
}
```
**Auth**: Admin only

#### Get Client Details
```http
GET /api/v1/clients/{client_id}
```
**Auth**: User or Admin

### SIM Card Management

#### List SIM Cards
```http
GET /api/v1/sims?client_id=optional
```
**Auth**: User or Admin

#### Create SIM Cards (Single or Bulk)
```http
POST /api/v1/sims
Content-Type: application/json

# Single SIM
{
    "client_id": "JSmith0001",
    "sim_number": "1234567890",
    "msisdn": "1234567890123456",
    "fup_gb": 50
}

# Bulk SIM Creation
{
    "sim_cards": [
        {
            "client_id": "JSmith0001",
            "sim_number": "1234567890",
            "msisdn": "1234567890123456",
            "fup_gb": 50
        },
        {
            "client_id": "JSmith0001",
            "sim_number": "0987654321",
            "msisdn": "6543210987654321",
            "fup_gb": 100
        }
    ]
}
```
**Auth**: Admin only

### Usage Data

#### Get Usage Records
```http
GET /api/v1/usage?client_id=optional&limit=100&offset=0
```
**Auth**: User or Admin

#### Create Usage Record
```http
POST /api/v1/usage
Content-Type: application/json

{
    "client_id": "JSmith0001",
    "sim_number": "1234567890",
    "msisdn": "1234567890123456",
    "total_usage_gb": 25.5,
    "date_from": "2024-01-01",
    "date_to": "2024-01-31",
    "fup_reached": false
}
```
**Auth**: Admin only

### Analytics

#### Usage Summary
```http
GET /api/v1/analytics/summary?client_id=optional
```
**Auth**: User or Admin

#### Protocol Analysis
```http
GET /api/v1/analytics/protocols?client_id=optional
```
**Auth**: User or Admin

## 💻 Integration Examples

### Python Example
```python
import requests

class SIMAnalyticsAPI:
    def __init__(self, api_key, base_url="http://your-domain:5001/api/v1"):
        self.api_key = api_key
        self.base_url = base_url
        self.headers = {
            'X-API-Key': api_key,
            'Content-Type': 'application/json'
        }
    
    def create_client_with_sims(self, client_name, sim_data):
        # Create client
        client_response = requests.post(
            f"{self.base_url}/clients",
            headers=self.headers,
            json={"client_name": client_name}
        )
        
        if client_response.status_code == 201:
            client = client_response.json()['client']
            client_id = client['client_id']
            
            # Add client_id to each SIM
            for sim in sim_data:
                sim['client_id'] = client_id
            
            # Create SIMs
            sims_response = requests.post(
                f"{self.base_url}/sims",
                headers=self.headers,
                json={"sim_cards": sim_data}
            )
            
            return {
                'client': client,
                'sims': sims_response.json() if sims_response.status_code == 201 else None
            }
        
        return None

# Usage
api = SIMAnalyticsAPI("your_admin_api_key_here")
result = api.create_client_with_sims(
    "Tech Corporation", 
    [
        {"sim_number": "1234567890", "msisdn": "1234567890123456", "fup_gb": 50},
        {"sim_number": "0987654321", "msisdn": "6543210987654321", "fup_gb": 100}
    ]
)
```

### JavaScript Example
```javascript
class SIMAnalyticsAPI {
    constructor(apiKey, baseUrl = 'http://your-domain:5001/api/v1') {
        this.apiKey = apiKey;
        this.baseUrl = baseUrl;
        this.headers = {
            'X-API-Key': apiKey,
            'Content-Type': 'application/json'
        };
    }

    async createClientWithSims(clientName, simData) {
        try {
            // Create client
            const clientResponse = await fetch(`${this.baseUrl}/clients`, {
                method: 'POST',
                headers: this.headers,
                body: JSON.stringify({ client_name: clientName })
            });

            if (clientResponse.ok) {
                const clientResult = await clientResponse.json();
                const clientId = clientResult.client.client_id;

                // Add client_id to each SIM
                const simsWithClientId = simData.map(sim => ({
                    ...sim,
                    client_id: clientId
                }));

                // Create SIMs
                const simsResponse = await fetch(`${this.baseUrl}/sims`, {
                    method: 'POST',
                    headers: this.headers,
                    body: JSON.stringify({ sim_cards: simsWithClientId })
                });

                return {
                    client: clientResult.client,
                    sims: simsResponse.ok ? await simsResponse.json() : null
                };
            }
        } catch (error) {
            console.error('API Error:', error);
            return null;
        }
    }
}

// Usage
const api = new SIMAnalyticsAPI('your_admin_api_key_here');
```

### cURL Examples
```bash
# Create client
curl -X POST http://your-domain:5001/api/v1/clients \
  -H "X-API-Key: your_admin_api_key" \
  -H "Content-Type: application/json" \
  -d '{"client_name": "John Smith"}'

# Create multiple SIMs
curl -X POST http://your-domain:5001/api/v1/sims \
  -H "X-API-Key: your_admin_api_key" \
  -H "Content-Type: application/json" \
  -d '{
    "sim_cards": [
      {
        "client_id": "JSmith0001",
        "sim_number": "1234567890",
        "msisdn": "1234567890123456",
        "fup_gb": 50
      }
    ]
  }'
```

## 🔒 Rate Limiting
- Default rate limit: 1000 requests/hour per API key
- Rate limits are configurable per key
- HTTP 429 returned when limit exceeded

## 📊 Error Handling
- **200**: Success
- **201**: Created
- **400**: Bad Request
- **401**: Unauthorized (invalid API key)
- **403**: Forbidden (insufficient permissions)
- **404**: Not Found
- **409**: Conflict (resource already exists)
- **429**: Rate Limit Exceeded
- **500**: Internal Server Error

## 🆘 Support
For API key generation and management, access the admin panel at:
```
http://your-domain:5000 → API Key Management
```

## 📋 Use Case: External System Integration

The API is designed to allow external systems to:

1. **Create clients and provision SIM cards**
   ```python
   # External provisioning system
   api.create_client_with_sims("New Customer", [
       {"sim_number": "1234567890", "msisdn": "1234567890123456", "fup_gb": 50}
   ])
   ```

2. **Monitor usage and analytics**
   ```python
   # Dashboard system
   summary = api.get_analytics_summary("JSmith0001")
   protocols = api.get_protocol_analysis("JSmith0001")
   ```

3. **Automated reporting**
   ```python
   # Reporting system
   usage_data = api.get_usage_records(client_id="JSmith0001", limit=100)
   ```

This comprehensive API enables seamless integration with billing systems, customer portals, monitoring dashboards, and automated provisioning workflows.