# API Overview

STA Connector provides REST APIs and real-time WebSocket channels via Phoenix Framework:

- **Outbound API** - File upload operations
- **Admin API** - Administration and monitoring
- **Phoenix Channels** - Real-time updates via WebSocket

## Base URLs

| Environment | Outbound API | Admin API |
|-------------|--------------|-----------|
| Development | `http://localhost:4000/api/v1` | `http://localhost:4000/admin` |
| Production | `https://your-domain/api/v1` | `https://your-domain/admin` |

## Authentication

### Phoenix Token Authentication

All API endpoints use Phoenix Token authentication:

```bash
curl -H "Authorization: Bearer your-phoenix-token" \
  http://localhost:4000/api/v1/health
```

Tokens can be obtained via the authentication endpoint:

```bash
curl -X POST http://localhost:4000/api/auth \
  -H "Content-Type: application/json" \
  -d '{"api_key": "your-api-key"}'
```

Response:

```json
{
  "token": "SFMyNTY.g2gDaAJh...",
  "expires_at": "2026-02-01T10:30:00Z"
}
```

### Admin API

Admin endpoints require elevated privileges:

```bash
curl -H "Authorization: Bearer your-admin-token" \
  http://localhost:4000/admin/health
```

## Phoenix Channels (WebSocket)

Connect to real-time updates via Phoenix Channels at:

```
ws://localhost:4000/socket/websocket
wss://your-domain/socket/websocket (production)
```

### Available Channels

| Channel | Description | Events |
|---------|-------------|--------|
| `files:lobby` | Real-time file updates | `file:created`, `file:updated`, `file:completed`, `file:failed` |
| `metrics:lobby` | Live metrics streaming | `metrics:update`, `metrics:alert` |
| `logs:lobby` | Log streaming | `log:info`, `log:warning`, `log:error` |
| `health:status` | Health status updates | `health:update`, `health:degraded`, `health:recovered` |
| `admin:notifications` | Admin alerts | `alert:warning`, `alert:critical`, `config:changed` |

### Channel Connection Example (JavaScript)

```javascript
import { Socket } from "phoenix"

const socket = new Socket("ws://localhost:4000/socket", {
  params: { token: "your-phoenix-token" }
})

socket.connect()

// Join files channel
const filesChannel = socket.channel("files:lobby", {})
filesChannel.join()
  .receive("ok", resp => console.log("Joined files channel", resp))
  .receive("error", resp => console.log("Unable to join", resp))

// Listen for file updates
filesChannel.on("file:completed", payload => {
  console.log("File completed:", payload.file_id)
})

filesChannel.on("file:failed", payload => {
  console.log("File failed:", payload.file_id, payload.error)
})

// Join metrics channel
const metricsChannel = socket.channel("metrics:lobby", {})
metricsChannel.join()

metricsChannel.on("metrics:update", payload => {
  console.log("Metrics:", payload)
})
```

### Channel Connection Example (Elixir)

```elixir
{:ok, socket} = Phoenix.Channels.Socket.connect(
  "ws://localhost:4000/socket/websocket",
  params: %{token: "your-phoenix-token"}
)

{:ok, _reply, files_channel} = Phoenix.Channels.Socket.join(socket, "files:lobby")

receive do
  {:event, "file:completed", payload} ->
    IO.puts("File completed: #{payload["file_id"]}")
end
```

## API Structure

### Outbound API Endpoints

| Method | Endpoint | Description | Documentation |
|--------|----------|-------------|---------------|
| GET | `/api/v1/health` | Health check | [Outbound API](/api/outbound) |
| POST | `/api/v1/files` | Submit file for upload | [Outbound API](/api/outbound) |
| GET | `/api/v1/files/{id}/status` | Check upload status | [Outbound API](/api/outbound) |

### Admin API Endpoints

| Method | Endpoint | Description | Documentation |
|--------|----------|-------------|---------------|
| GET | `/admin/health` | Health check with details | [Admin API](/api/admin) |
| GET | `/admin/config` | Get configuration | [Admin API](/api/admin) |
| PATCH | `/admin/config` | Update configuration | [Admin API](/api/admin) |
| GET | `/admin/metrics` | Get metrics | [Admin API](/api/admin) |
| GET | `/admin/files` | List processed files | [Admin API](/api/admin) |
| POST | `/admin/retry/{id}` | Retry failed file | [Admin API](/api/admin) |
| POST | `/admin/poller/trigger` | Trigger poll cycle | [Admin API](/api/admin) |

## Common Endpoints

### Health Check (Outbound API)

```http
GET /api/v1/health
```

Response:

```json
{
  "status": "healthy",
  "sta_connection": "ok",
  "database": "ok",
  "uptime_seconds": 86400,
  "version": "1.0.0"
}
```

### Health Check (Admin API)

```http
GET /admin/health
```

Response:

```json
{
  "status": "healthy",
  "version": "1.0.0",
  "checks": {
    "store": "healthy",
    "metrics": "healthy",
    "poller": "idle"
  },
  "timestamp": "2026-01-31T10:30:00Z"
}
```

## Request/Response Format

### Request Headers

| Header | Required | Description |
|--------|----------|-------------|
| `Authorization` | Yes | Bearer token (Phoenix Token) |
| `Content-Type` | For POST/PATCH | `application/json` |

### Success Response

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "protocol": "2026013100001234",
  "status": "uploaded",
  "created_at": "2026-01-31T10:30:00Z"
}
```

### Error Response

```json
{
  "error": "validation_error",
  "message": "system is required"
}
```

## HTTP Status Codes

| Code | Description |
|------|-------------|
| 200 | Success |
| 201 | Created |
| 202 | Accepted (async operation) |
| 400 | Bad Request |
| 401 | Unauthorized |
| 404 | Not Found |
| 409 | Conflict |
| 429 | Too Many Requests |
| 500 | Internal Server Error |
| 502 | Bad Gateway (STA error) |
| 503 | Service Unavailable |

## Error Codes

| Code | Description |
|------|-------------|
| `invalid_request` | Malformed request body |
| `validation_error` | Request validation failed |
| `invalid_content` | Invalid base64 content |
| `not_found` | Resource not found |
| `sta_error` | STA WebService error |
| `sta_auth_error` | STA authentication failed |
| `sta_rate_limit` | STA rate limit exceeded |
| `sta_connection_error` | Failed to connect to STA |
| `internal_error` | Internal server error |

## Rate Limiting

The connector enforces BCB rate limits:

- **Maximum 10** simultaneous uploads per institution
- **Maximum 120** queries per minute per institution

When rate limited:

```http
HTTP/1.1 429 Too Many Requests

{
  "error": "sta_rate_limit",
  "message": "STA rate limit exceeded"
}
```

## Pagination

List endpoints support pagination:

```http
GET /admin/files?limit=50&offset=100
```

| Parameter | Default | Max | Description |
|-----------|---------|-----|-------------|
| `limit` | 100 | 1000 | Items per page |
| `offset` | 0 | - | Skip items |

Response includes pagination metadata:

```json
{
  "files": [...],
  "total": 500,
  "limit": 50,
  "offset": 100,
  "has_more": true
}
```

## Filtering

List endpoints support filtering:

```http
GET /admin/files?status=failed&system=SPI&start_date=2026-01-01
```

| Filter | Type | Description |
|--------|------|-------------|
| `status` | string | Filter by status |
| `system` | string | Filter by BCB system |
| `start_date` | ISO 8601 | Start date |
| `end_date` | ISO 8601 | End date |

## Quick Examples

### Submit a File

```bash
curl -X POST http://localhost:4000/api/v1/files \
  -H "Authorization: Bearer your-phoenix-token" \
  -H "Content-Type: application/json" \
  -d '{
    "system": "CCS",
    "file_type": "ARQC001",
    "data": {
      "content": "'$(base64 -w0 file.txt)'"
    },
    "destination": {
      "ispb": "00000000"
    }
  }'
```

### Check Status

```bash
curl -H "Authorization: Bearer your-phoenix-token" \
  http://localhost:4000/api/v1/files/550e8400-.../status
```

### Get Metrics

```bash
curl -H "Authorization: Bearer your-admin-token" \
  http://localhost:4000/admin/metrics
```

### Retry Failed File

```bash
curl -H "Authorization: Bearer your-admin-token" -X POST \
  http://localhost:4000/admin/retry/550e8400-...
```

## Next Steps

- [Outbound API](/api/outbound) - File upload endpoints
- [Admin API](/api/admin) - Administration and monitoring
- [Phoenix Channels](/api/channels) - Real-time WebSocket updates
