# StatusPage API Migration Guide

## Overview

The `StatusPageAPI.swift` file has been updated to align with the official API reference documentation. This guide outlines the changes and how they affect your code.

## Key Changes

### 1. Base URL Structure

**Before:**
- Single base URL: `https://statuspage.me/user/api/v1`
- Feature base URL: `https://statuspage.me/user/api`

**After:**
- Base URL: `https://statuspage.me/user/api`
- V1 Base URL: `https://statuspage.me/user/api/v1`

The API now properly distinguishes between v1 endpoints (which require API scopes) and non-v1 endpoints.

### 2. Authentication Headers

All endpoints now use **both** headers for maximum compatibility:
- `X-API-Key: YOUR_API_KEY`
- `Authorization: Bearer YOUR_API_KEY`

### 3. New Endpoint Categories

#### Maintenances (v1 endpoints)
- `fetchMaintenances()` - GET /v1/maintenances
- `fetchMaintenance(id:)` - GET /v1/maintenances/:id
- `createMaintenance(...)` - POST /v1/maintenances
- `updateMaintenance(...)` - PATCH /v1/maintenances/:id
- `deleteMaintenance(id:)` - DELETE /v1/maintenances/:id

#### Heartbeats
- `fetchHeartbeats(statusPageId:)` - GET /status-pages/:id/heartbeats
- `fetchHeartbeat(id:)` - GET /heartbeats/:id
- `createHeartbeat(...)` - POST /status-pages/:id/heartbeats
- `updateHeartbeat(...)` - PUT /heartbeats/:id
- `deleteHeartbeat(id:)` - DELETE /heartbeats/:id
- `regenerateHeartbeatToken(id:)` - POST /heartbeats/:id/regenerate-token
- `fetchHeartbeatPings(id:)` - GET /heartbeats/:id/pings

#### Incident Tasks
- `fetchIncidentTasks(incidentId:)` - GET /incidents/:id/tasks
- `createIncidentTask(...)` - POST /incidents/:id/tasks
- `updateIncidentTask(...)` - PATCH /incidents/:id/tasks/:task_id
- `deleteIncidentTask(...)` - DELETE /incidents/:id/tasks/:task_id

#### Notification Channels
- `fetchNotificationChannels()` - GET /notification-channels
- `createNotificationChannel(...)` - POST /notification-channels
- `updateNotificationChannel(...)` - PUT /notification-channels/:id
- `deleteNotificationChannel(channelId:)` - DELETE /notification-channels/:id
- `testNotificationChannel(channelId:)` - POST /notification-channels/:id/test
- `resendChannelVerification(channelId:)` - POST /notification-channels/:id/resend-verification

#### Enhanced Monitor Operations
- `fetchMonitor(id:)` - GET /v1/monitors/:id (NEW)
- `fetchMonitorAvailability(id:)` - GET /v1/monitors/:id/availability (NEW)
- `fetchMonitorResults(id:)` - GET /monitors/:id/results (NEW)
- `deleteMonitor(id:)` - DELETE /monitors/:id (NEW)

#### Enhanced Team Operations
- `fetchTeam(id:)` - GET /teams/:id (NEW)
- `createTeam(name:)` - POST /teams (NEW)
- `updateTeam(id:name:)` - PUT /teams/:id (NEW)
- `deleteTeam(id:)` - DELETE /teams/:id (NEW)

#### Enhanced Status Page Operations
- `fetchStatusPage(id:)` - GET /v1/status-pages/:id (NEW)
- `createStatusPage(name:slug:)` - POST /status-pages (NEW)
- `deleteStatusPage(id:)` - DELETE /teams/:id/status-pages/:id (NEW)

#### Enhanced Incident Operations
- `fetchIncident(id:)` - GET /v1/incidents/:id (NEW)
- `deleteIncident(id:)` - DELETE /v1/incidents/:id (NEW)
- `createIncidentUpdate(...)` - POST /v1/incidents/:id/updates (NEW)
- `assignIncident(id:userId:)` - PATCH /incidents/:id/assign (NEW)

#### Dashboard
- `fetchDashboardSummary()` - GET /dashboard/summary (NEW)

#### On-Call
- `fetchOnCallScheduleMembers(scheduleId:)` - GET /on-call/schedules/:id/current (NEW)

### 4. Updated Method Signatures

#### Components
**Before:**
```swift
fetchComponents(pageId: String) async throws -> [Component]
createComponent(pageId: String, name: String, ...) async throws -> Component
updateComponent(pageId: String, componentId: String, ...) async throws -> Component
deleteComponent(pageId: String, componentId: String) async throws
```

**After:**
```swift
fetchComponents(statusPageId: String? = nil) async throws -> [Component]
createComponent(name: String, ...) async throws -> Component
updateComponent(componentId: String, ...) async throws -> Component
deleteComponent(componentId: String) async throws
```

#### Component Groups
**Before:**
```swift
fetchGroups(pageId: String) async throws -> [ComponentGroup]
createGroup(pageId: String, name: String) async throws -> ComponentGroup
updateGroup(pageId: String, groupId: String, name: String?) async throws -> ComponentGroup
deleteGroup(pageId: String, groupId: String) async throws
```

**After:**
```swift
fetchGroups() async throws -> [ComponentGroup]
createGroup(name: String) async throws -> ComponentGroup
updateGroup(groupId: String, name: String?) async throws -> ComponentGroup
deleteGroup(groupId: String) async throws
```

#### Monitor Operations
**Before:**
```swift
pauseMonitor(id:) // Used POST /monitors/:id/pause
resumeMonitor(id:) // Used POST /monitors/:id/resume
```

**After:**
```swift
pauseMonitor(id:) // Uses PUT /monitors/:id with {"enabled": false}
resumeMonitor(id:) // Uses PUT /monitors/:id with {"enabled": true}
```

### 5. New Data Models

The following new structs have been added:

```swift
// Maintenances
struct Maintenance: Codable, Identifiable, Hashable

// Heartbeats
struct Heartbeat: Codable, Identifiable, Hashable
struct HeartbeatPing: Codable, Hashable

// Monitor Analytics
struct MonitorAvailability: Codable, Hashable

// Incident Tasks
struct IncidentTask: Codable, Identifiable, Hashable
struct CreateIncidentTaskRequest: Codable
struct UpdateIncidentTaskRequest: Codable

// On-Call
struct OnCallSchedule: Codable, Identifiable, Hashable
struct OnCallMember: Codable, Hashable

// Notifications
struct NotificationChannel: Codable, Identifiable, Hashable
struct CreateNotificationChannelRequest: Codable

// Incident Updates
struct CreateIncidentUpdateRequest: Codable

// Maintenance Requests
struct CreateMaintenanceRequest: Codable
struct UpdateMaintenanceRequest: Codable
```

### 6. Endpoint Path Corrections

Several endpoints have been corrected to match the actual API:

| Old Path | New Path | Notes |
|----------|----------|-------|
| `/v1/incidents/:id/acknowledge` | `/incidents/:id/acknowledge` | Non-v1 endpoint |
| `/v1/incidents/:id/escalate` | `/incidents/:id/escalate` | Non-v1 endpoint |
| `/v1/monitors/:id/run` | `/monitors/:id/run` | Non-v1 endpoint |
| `/v1/on-call/...` | `/on-call/...` | Non-v1 endpoint |
| `/v1/teams/...` | `/teams/...` | Non-v1 endpoint |
| `/v1/analytics/...` | `/analytics/...` | Non-v1 endpoint |
| `/v1/status-pages/:id/components` | `/components?status_page_id=:id` | Different structure |
| `/v1/status-pages/:id/groups` | `/component-groups` | Different structure |

## Migration Steps

### 1. Update Component/Group Method Calls

If you're using the old signatures with `pageId` parameter:

**Before:**
```swift
let components = try await StatusPageAPI.shared.fetchComponents(pageId: "123")
```

**After:**
```swift
let components = try await StatusPageAPI.shared.fetchComponents(statusPageId: "123")
// Or if you want all components:
let allComponents = try await StatusPageAPI.shared.fetchComponents()
```

### 2. Add Maintenance Support

If you need to manage maintenances:

```swift
// Fetch all maintenances
let maintenances = try await StatusPageAPI.shared.fetchMaintenances()

// Create a maintenance
let maintenance = try await StatusPageAPI.shared.createMaintenance(
    title: "Scheduled Database Migration",
    message: "We'll be performing database maintenance",
    scheduledFor: Date().addingTimeInterval(3600),
    scheduledUntil: Date().addingTimeInterval(7200),
    affectedComponents: ["component-id-1", "component-id-2"]
)

// Update a maintenance
let updated = try await StatusPageAPI.shared.updateMaintenance(
    id: maintenance.id,
    status: "in_progress"
)
```

### 3. Add Heartbeat Support

If you need to manage heartbeats:

```swift
// Fetch heartbeats for a status page
let heartbeats = try await StatusPageAPI.shared.fetchHeartbeats(statusPageId: "page-123")

// Create a heartbeat
let heartbeat = try await StatusPageAPI.shared.createHeartbeat(
    statusPageId: "page-123",
    name: "Background Worker",
    intervalSeconds: 300
)

// Check heartbeat pings
let pings = try await StatusPageAPI.shared.fetchHeartbeatPings(id: heartbeat.id)
```

### 4. Use Incident Tasks

```swift
// Fetch tasks for an incident
let tasks = try await StatusPageAPI.shared.fetchIncidentTasks(incidentId: "incident-123")

// Create a task
let task = try await StatusPageAPI.shared.createIncidentTask(
    incidentId: "incident-123",
    description: "Investigate root cause"
)

// Mark as completed
let completed = try await StatusPageAPI.shared.updateIncidentTask(
    incidentId: "incident-123",
    taskId: task.id,
    completed: true
)
```

## API Scopes

The v1 endpoints require specific API key scopes:

| Endpoint Pattern | Required Scope |
|------------------|----------------|
| `/v1/status-pages*` | `ScopeStatusPagesRead` |
| `/v1/monitors*` | `ScopeMonitorsRead` |
| `/v1/monitors/:id/availability` | `ScopeAnalyticsRead` |
| `/v1/incidents` (GET) | `ScopeIncidentsRead` |
| `/v1/incidents` (POST/PATCH/DELETE) | `ScopeIncidentsWrite` |
| `/v1/maintenances` (GET) | `ScopeMaintenancesRead` |
| `/v1/maintenances` (POST/PATCH/DELETE) | `ScopeMaintenancesWrite` |

Ensure your API key has the appropriate scopes for the operations you need.

## Breaking Changes Summary

1. **Component/Group methods** - `pageId` parameter removed or made optional
2. **Monitor pause/resume** - Implementation changed from POST to PUT
3. **Base URL handling** - Internal change, but affects request construction
4. **Removed methods** - `switchTeam(teamId:)` was a placeholder and has been removed

## Testing Checklist

- [ ] Test status page fetching
- [ ] Test monitor operations (fetch, pause, resume)
- [ ] Test incident operations (create, update, acknowledge, escalate)
- [ ] Test component operations with new signatures
- [ ] Test group operations with new signatures
- [ ] Test new maintenance endpoints if needed
- [ ] Test new heartbeat endpoints if needed
- [ ] Verify API key has required scopes
- [ ] Check error handling for scope-related failures

## Additional Resources

- Full API Reference: See the provided API documentation
- API Key Management: `/user/api/security/api-keys` (session-only, not API-key accessible)
- Excluded Endpoints: API key management endpoints cannot be accessed via API keys

## Notes

- All endpoints under `/user/api/` are accessible via API key authentication
- Endpoints under `/user/api/security/api-keys*` are explicitly excluded from API key auth
- The API wraps most responses in `{"data": ...}` - the SDK handles this automatically
- Date encoding uses ISO8601 format
- Property names are automatically converted between snake_case and camelCase
