# Quick Start Guide - Updated API

## TL;DR

✅ **The API has been updated to match the official StatusPage.me API reference**  
✅ **UI has been updated to work with the new API**  
✅ **All existing features work correctly**  
✅ **100+ new endpoints are now available**

## What Changed?

### For Component/Group Operations

```swift
// OLD ❌
let components = try await StatusPageAPI.shared.fetchComponents(pageId: "page123")
let groups = try await StatusPageAPI.shared.fetchGroups(pageId: "page123")
try await StatusPageAPI.shared.updateComponent(pageId: "page123", componentId: "comp1", name: "New Name")
try await StatusPageAPI.shared.deleteComponent(pageId: "page123", componentId: "comp1")

// NEW ✅
let components = try await StatusPageAPI.shared.fetchComponents(statusPageId: "page123")
let groups = try await StatusPageAPI.shared.fetchGroups(statusPageId: "page123")
try await StatusPageAPI.shared.updateComponent(componentId: "comp1", name: "New Name")
try await StatusPageAPI.shared.deleteComponent(componentId: "comp1")
```

**Key Points:**
1. ⚠️ **`fetchGroups()` now REQUIRES `statusPageId` parameter**
2. ⚠️ **`createGroup()` now REQUIRES `statusPageId` parameter**
3. `fetchComponents()` has `statusPageId` as optional parameter (filter recommended)
4. Component update/delete no longer need `pageId`

## Running the App

1. **Build and run** - No changes needed to your build process
2. **Add API key** - Open Settings and paste your API key
3. **Use the app** - Everything works as before

## New Features You Can Use

### Maintenances

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

// Create a maintenance window
let maintenance = try await StatusPageAPI.shared.createMaintenance(
    title: "Database Upgrade",
    message: "Brief downtime expected",
    scheduledFor: Date().addingTimeInterval(3600),
    scheduledUntil: Date().addingTimeInterval(7200),
    affectedComponents: ["comp1", "comp2"]
)
```

### Heartbeats

```swift
// Fetch heartbeats
let heartbeats = try await StatusPageAPI.shared.fetchHeartbeats(statusPageId: "page123")

// Create a heartbeat monitor
let heartbeat = try await StatusPageAPI.shared.createHeartbeat(
    statusPageId: "page123",
    name: "Background Worker",
    intervalSeconds: 300
)
```

### Incident Tasks

```swift
// Add tasks to incidents
let task = try await StatusPageAPI.shared.createIncidentTask(
    incidentId: "incident123",
    description: "Check database logs"
)

// Mark complete
try await StatusPageAPI.shared.updateIncidentTask(
    incidentId: "incident123",
    taskId: task.id,
    completed: true
)
```

### Monitor Analytics

```swift
// Get availability data
let availability = try await StatusPageAPI.shared.fetchMonitorAvailability(id: "monitor123")
print("Uptime: \(availability.uptimePercentage)%")
```

### Teams

```swift
// Manage teams
let teams = try await StatusPageAPI.shared.fetchTeams()
let team = try await StatusPageAPI.shared.createTeam(name: "Engineering")
```

### Notification Channels

```swift
// Setup notifications
let channel = try await StatusPageAPI.shared.createNotificationChannel(
    type: "email",
    name: "Team Email",
    config: ["address": "team@example.com"]
)

// Test it
try await StatusPageAPI.shared.testNotificationChannel(channelId: channel.id)
```

## Documentation

### 📖 For Reference
- **API_QUICK_REFERENCE.md** - Quick lookup of all available methods
- **API_MIGRATION_GUIDE.md** - Detailed migration information
- **UI_UPDATE_SUMMARY.md** - UI-specific changes and testing
- **CHANGES_VISUAL_GUIDE.md** - Visual comparison of changes

### 🧪 Testing

Run through this quick test:

```swift
// 1. Test status pages
let pages = try await StatusPageAPI.shared.fetchStatusPages()

// 2. Test components (new signature)
let components = try await StatusPageAPI.shared.fetchComponents(statusPageId: pages.first?.id)

// 3. Test groups (REQUIRES statusPageId)
let groups = try await StatusPageAPI.shared.fetchGroups(statusPageId: pages.first?.id ?? "")

// 4. Test update (new signature)
if let component = components.first {
    try await StatusPageAPI.shared.updateComponent(
        componentId: component.id,
        status: "operational"
    )
}

// 5. Test new features
let maintenances = try await StatusPageAPI.shared.fetchMaintenances()
let heartbeats = try await StatusPageAPI.shared.fetchHeartbeats(statusPageId: pages.first?.id ?? "")
```

## Troubleshooting

### "API key is missing" Error
➡️ Go to Settings and add your API key

### "Access forbidden" Error (HTTP 403)
➡️ Your API key needs the required scopes. Check the API_QUICK_REFERENCE.md for scope requirements.

### "Components not available" Error (HTTP 401)
➡️ Components may not be available on your plan, or your API key needs `ScopeStatusPagesRead` scope.

### Components Not Showing Up
➡️ Make sure you're using `fetchComponents(statusPageId: "...")` with the correct page ID

### Groups Not Loading
➡️ Make sure you're using `fetchGroups(statusPageId: "...")` with the correct page ID - **this parameter is required!**

### "status_page_id is required" Error (HTTP 400)
➡️ The backend requires `status_page_id` for `fetchGroups()` and `createGroup()`. Always pass a valid status page ID.

## Code Examples

### Adding a Maintenance Tab

```swift
// In StatusPageDetailView, add a new tab:
case maintenance = "Maintenance"

// Add the view:
struct MaintenanceListView: View {
    @State private var maintenances: [Maintenance] = []
    
    var body: some View {
        List(maintenances) { maintenance in
            VStack(alignment: .leading) {
                Text(maintenance.title)
                    .font(.headline)
                Text(maintenance.status)
                    .font(.caption)
                    .foregroundColor(.secondary)
            }
        }
        .task {
            maintenances = (try? await StatusPageAPI.shared.fetchMaintenances()) ?? []
        }
    }
}
```

### Adding Heartbeat Monitoring

```swift
struct HeartbeatMonitorView: View {
    let statusPageId: String
    @State private var heartbeats: [Heartbeat] = []
    
    var body: some View {
        List(heartbeats) { heartbeat in
            HStack {
                VStack(alignment: .leading) {
                    Text(heartbeat.name)
                        .font(.headline)
                    Text("Interval: \(heartbeat.intervalSeconds)s")
                        .font(.caption)
                        .foregroundColor(.secondary)
                }
                Spacer()
                Circle()
                    .fill(heartbeat.status == "up" ? Color.green : Color.red)
                    .frame(width: 12, height: 12)
            }
        }
        .task {
            heartbeats = (try? await StatusPageAPI.shared.fetchHeartbeats(statusPageId: statusPageId)) ?? []
        }
    }
}
```

### Adding Task Management to Incidents

```swift
// In IncidentDetailView, add:
@State private var tasks: [IncidentTask] = []

// In the body:
if !tasks.isEmpty {
    GroupBox("Tasks") {
        VStack(alignment: .leading, spacing: 8) {
            ForEach(tasks) { task in
                HStack {
                    Image(systemName: task.completed ? "checkmark.circle.fill" : "circle")
                        .foregroundColor(task.completed ? .green : .secondary)
                    Text(task.description)
                    Spacer()
                }
                .onTapGesture {
                    Task {
                        try? await StatusPageAPI.shared.updateIncidentTask(
                            incidentId: incident.id,
                            taskId: task.id,
                            completed: !task.completed
                        )
                        // Refresh tasks
                    }
                }
            }
        }
    }
}

// Load tasks:
.task {
    tasks = (try? await StatusPageAPI.shared.fetchIncidentTasks(incidentId: incident.id)) ?? []
}
```

## Performance Tips

### Use Concurrent Fetching

```swift
// Good ✅
async let pages = StatusPageAPI.shared.fetchStatusPages()
async let monitors = StatusPageAPI.shared.fetchMonitors()
async let incidents = StatusPageAPI.shared.fetchIncidents()

let (allPages, allMonitors, allIncidents) = try await (pages, monitors, incidents)
```

### Cache When Appropriate

```swift
// Cache groups since they don't change often
@State private var cachedGroups: [String: [ComponentGroup]] = [:]  // Keyed by pageId
@State private var groupsLastFetched: [String: Date] = []

func fetchGroupsIfNeeded(for pageId: String) async {
    if let lastFetch = groupsLastFetched[pageId], Date().timeIntervalSince(lastFetch) < 300 {
        return // Use cached version
    }
    cachedGroups[pageId] = (try? await StatusPageAPI.shared.fetchGroups(statusPageId: pageId)) ?? []
    groupsLastFetched[pageId] = Date()
}
```

### Handle Errors Gracefully

```swift
do {
    let components = try await StatusPageAPI.shared.fetchComponents(statusPageId: pageId)
    self.components = components
    self.error = nil
} catch StatusPageAPI.APIError.httpStatus(403) {
    self.error = "Check your API key scopes"
} catch {
    self.error = "Failed to load: \(error.localizedDescription)"
}
```

## API Key Scopes

When creating API keys, ensure they have the necessary scopes:

| Feature | Required Scope |
|---------|----------------|
| View status pages | `ScopeStatusPagesRead` |
| View monitors | `ScopeMonitorsRead` |
| View analytics | `ScopeAnalyticsRead` |
| View incidents | `ScopeIncidentsRead` |
| Create/edit incidents | `ScopeIncidentsWrite` |
| View maintenances | `ScopeMaintenancesRead` |
| Create/edit maintenances | `ScopeMaintenancesWrite` |

## Questions?

1. **Check the quick reference**: API_QUICK_REFERENCE.md
2. **Review examples**: This file has code examples
3. **Check the migration guide**: API_MIGRATION_GUIDE.md has detailed explanations
4. **Visual comparison**: CHANGES_VISUAL_GUIDE.md shows before/after

## Summary

You're ready to go! The main things to remember:

1. ✅ `fetchComponents()` takes optional `statusPageId:` (recommended for filtering)
2. ⚠️ **`fetchGroups()` REQUIRES `statusPageId:` parameter** (API requirement)
3. ⚠️ **`createGroup()` REQUIRES `statusPageId:` parameter** (API requirement)
4. ✅ `updateComponent()` doesn't need `pageId` (parameter removed)
5. ✅ `deleteComponent()` doesn't need `pageId` (parameter removed)
6. ✅ 100+ new endpoints available for new features
7. ✅ All existing UI features work correctly

Happy coding! 🚀
